If you need to bootstrap a GCP project’s infrastructure, one of the first things you will want is a service account. The creation of the service account, creating its key, and then assigning binding roles can all be done from the GCP console but for scripting purposes can also be done using the gcloud utility.
Once you have gcloud installed, you can create a service account like below:
# get list of project ids gcloud projects list --format='value(project_id)' # set project by id gcloud config set project <projectId> # create service account in project gcloud iam service-accounts create testSvcAcct1 --display-name "test svc account" --project=<projectId>
The key for this service account, can be downloaded.
# get full email id of new service account fullId=$(gcloud iam service-accounts list --filter="email ~ ^testSvcAcct1" --format='value(email)') # download key for service account gcloud iam service-accounts keys create testSvcAcct1.json --iam-account $fullId
And then IAM roles bound to the service account.
# bind IAM role to service account gcloud projects add-iam-policy-binding <projectId> --member=serviceAccount:$fullId --role=roles/logging.logWriter # bind another role gcloud projects add-iam-policy-binding <projectId> --member=serviceAccount:$fullId --role=roles/monitoring.metricWriter # validate that service account has two roles gcloud projects get-iam-policy <projectId> --flatten="bindings[].members" --filter="bindings.members=serviceAccount:$fullId" --format="value(bindings.role)"
To use this service account for further provisioning, impersonate and assume its identity using the downloaded key.
# assume service account identity gcloud auth activate-service-account $fullId --key-file=testSvcAcct1.json # validate that service account is now being used gcloud auth list
REFERENCES
google, gcloud iam service-accounts