GCP - Impersonate Service Account from Local Machine

Viewed 40

I have used AWS in the past. So I might be trying to compare the behavior with GCP. Bear with me and provide the steps to do things in a correct way.

What I did:

  • I create a service account in GCP with storage object viewer role.
  • I also create a key-pair and downloaded the json file in my local.

If I have gcloud/gsutil installed in my local machine, How can I assume/impersonate the service account and work on GCP resources?

Where should i keep the downloaded json file? I already referred to this - https://cloud.google.com/iam/docs/creating-managing-service-account-keys#creating


I downloaded file as key.json and kept in my home directory. Then I did this.

export GOOGLE_APPLICATION_CREDENTIALS="~/key.json"

Execute this command

gsutil cp dummy.txt gs://my-bucket/

Ideally, it should NOT work. but I am able to upload files.

1 Answers

You can set the path to your service account in env (when using Google Cloud SDKs):

#linux
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/path/to/serviceAccountFile.json"

#windows
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\path\to\serviceAccountFile.json"

If you don't have the key file, run the following command that'll download the key:

gcloud iam service-accounts keys create ./serviceAccount.json --iam-account=svc_name@project.iam.gserviceaccount.com

You can then use activate-service-account to use given service account as shown below:

gcloud auth activate-service-account --key-file=serviceAccount.json
Related