logo

GCP - Service Account Impersonation

What is 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.

Impersonating the service account =

  • A user gains permissions of a service account, or
  • A service account A gains permissions of service account B.

When to impersonate a service account?

  • change a user's permissions without changing your IAM policies.
  • temporarily grant a user elevated access.
  • test whether a specific set of permissions is sufficient for a task.
  • locally develop applications that can only run as a service account.
  • authenticate applications that run outside of Google Cloud.

How does impersonation work?

Technically "impersonation" means granting the principal (a user or another service account) the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator) on the service account. So that the authenticated principal gets a token for the service account, then uses that token to authenticate as the service account.

How to impersonate a service account?

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

What's the equivelant concept in AWS?

Google Cloud service account impersonation is similar to Amazon Web Services (AWS) Security Token Service API methods like AssumeRole.