Impersonate Google Cloud Service Account
Google Cloud Platform (GCP) uses so-called “Service accounts” to manage granular permissions:
A service account is a special kind of account typically used by an application or compute workload, such as a Compute Engine instance, rather than a person.
For example, you might have a service account dedicated to trigger a particular workload on GCP from Github actions. This allows us to have very granular permissions that we can give/revoke. So far so good, but sometimes we want to run the workflow from our local machine, for example to test it.
In such case we can impersonate the service account that we want to test and trigger the workload on its behalf like this:
- Create short-lived credentials and store them locally:
gcloud iam service-accounts keys create /local/path/to/credentials.json \
--iam-account "name-of-service-account@name-of-gcp-project.iam.gserviceaccount.com"
- Pass the credentials when runnning the workload (example with bigquery client):
from google.oauth2 import service_account
def get_impersonated_client(project):
= service_account.Credentials.from_service_account_file("/local/path/to/credentials.json")
credentials return bigquery.Client(credentials=credentials, project=project)
The returned client will act as if it was our target service account (and not using the credentials from the authenticated user on the local machine)
Read more about impersonation on GCP here.
/Fin
Any bugs, questions, comments, suggestions? Ping me on twitter or drop me an e-mail (fabridamicelli at gmail).
Share this article on your favourite platform: