logo

GCP - Service Account Impersonation

Service Account Impersonation: Service account impersonation is when a principal (user or service account) acts as another service account, pretending to be that service account. This is a common use case for temporarily delegating access to Google Cloud resources.

Grant to your user (e.g. [email protected]) the roles/iam.serviceAccountTokenCreator role on the service account (referred below as [email protected]).

gcloud iam service-accounts add-iam-policy-binding $SA@$PROJECT.iam.gserviceaccount.com \
--member="user:$EMAIL" --role="roles/iam.serviceAccountTokenCreator" --project $PROJECT

Enable the IAM Service Account Credentials API:

gcloud services enable iamcredentials.googleapis.com

Verify the impersonation:

gcloud auth --impersonate-service-account=$SA@$PROJECT.iam.gserviceaccount.com print-access-token

The access token should be printed to STDOUT while STDERR will have a warning:

WARNING: This command is using service account impersonation. All API calls will be executed as [[email protected]].

Call an API as the SA. Assuming that the service account has the Log Viewer role:

curl -H "Authorization: Bearer $(gcloud auth --impersonate-service-account=$SA@$PROJECT.iam.gserviceaccount.com print-access-token)" \
-H "Content-Type: application/json" https://logging.googleapis.com/v2/projects/$PROJECT/logs