Skip to the content
Fabian Lee : Software EngineerFabian Lee : Software Engineer
Cloud Operations and Development
  • Monitoring
  • Logging
  • Containers
  • Python

GCP: Creating gcp service account with IAM roles using gcloud

March 17, 2021
Categories: Containers

Although  the GCP console provides a manual interface for creating service accounts and assigning roles, it can also be done via the gcloud CLI.  Using gcloud, even the json key file for the service account can be generated, which is essential for automation.

The full Bash script, create_serviceaccount.sh can be found on github.  But  here are some critical snippets, showing service account creation,  downloading the json key credentials, and assigning roles.

# create service account
gcloud iam service-accounts create $newServiceAccount --display-name "test account" --project=$projectId

# get email identifier for service account
accountEmail=$(gcloud iam service-accounts list --project=$projectId --filter=$newServiceAccount --format="value(email)")

# download json key
gcloud iam service-accounts keys create $newServiceAccount-$projectId.json --iam-account $accountEmail

# assign IAM roles
for role in roles/storage.objectViewer roles/storage.objectCreator; do
gcloud projects add-iam-policy-binding $projectId --member=serviceAccount:$accountEmail --role=$role > /dev/null
done

If you need to operate as this new service account, you can use the downloaded json credentials file.

# operate as service account
# not the same as impersonation, which is a different concept
gcloud auth activate-service-account --key-file=<jsonKeyFile>

# validate that operations are now being performed as service account
gcloud auth list

 

 

REFERENCES

gcp docs, creating and managing service accounts

gcloud docs, iam service-accounts create

gcp docs, impersonate service accounts

NOTES

deleting service account

gcloud iam service-accounts delete $accountEmail

 

Categories: Containers Tags: account, create, gcloud, gcp, json, key, service

Post navigation

← Ansible: deleting a file path, but only if a symbolic link
Kubernetes: Updating an existing ConfigMap using kubectl replace →
© 2025 Fabian Lee : Software Engineer