diff --git a/retail/interactive-tutorials/user_environment_setup.sh b/retail/interactive-tutorials/user_environment_setup.sh index 9b7d823796..145e97933b 100644 --- a/retail/interactive-tutorials/user_environment_setup.sh +++ b/retail/interactive-tutorials/user_environment_setup.sh @@ -37,20 +37,46 @@ project_id=$1 echo "Project ID: $project_id" gcloud config set project "$project_id" -timestamp=$(date +%s) -service_account_id="service-acc-$timestamp" -echo "Service Account: $service_account_id" -# create service account (your service-acc-$timestamp) -gcloud iam service-accounts create "$service_account_id" +email=$(gcloud auth list --filter="status:ACTIVE account:$project_id.iam.gserviceaccount.com" --format="value(account)") +echo $email -# assign necessary roles to your new service account -for role in {retail.admin,editor} -do - gcloud projects add-iam-policy-binding "$project_id" --member="serviceAccount:$service_account_id@$project_id.iam.gserviceaccount.com" --role=roles/"${role}" -done +# check if user has service account active +if [ -z "$email" ] +then + # create a new service account + timestamp=$(date +%s) + service_account_id="service-acc-$timestamp" + echo "Service Account: $service_account_id" + gcloud iam service-accounts create "$service_account_id" +else + service_account_id="${email%@*}" + # log out of service account + gcloud auth revoke 2>/dev/null +fi +echo "$service_account_id" + +editor=$(gcloud projects get-iam-policy $project_id \ +--flatten="bindings[].members" \ +--format='table(bindings.role)' \ +--filter="bindings.members:$service_account_id ROLE=roles/editor") + +retail_admin=$(gcloud projects get-iam-policy $project_id \ +--flatten="bindings[].members" \ +--format='table(bindings.role)' \ +--filter="bindings.members:$service_account_id ROLE=roles/retail.admin") + +# check if any of the needed roles is missing +if [ -z "$editor" ] || [ -z "$retail_admin" ] +then + # assign necessary roles to your new service account. + for role in {retail.admin,editor} + do + gcloud projects add-iam-policy-binding "$project_id" --member="serviceAccount:$service_account_id@$project_id.iam.gserviceaccount.com" --role=roles/"${role}" + done + echo "Wait ~60 seconds to be sure the appropriate roles have been assigned to your service account" + sleep 60 +fi -echo "Wait ~60 seconds to be sure the appropriate roles have been assigned to your service account" -sleep 60 # upload your service account key file service_acc_email="$service_account_id@$project_id.iam.gserviceaccount.com" gcloud iam service-accounts keys create ~/key.json --iam-account "$service_acc_email"