Search code examples
google-cloud-platformgcloudservice-accounts

How can a service account authenticate in gcloud without changing the default gcloud account in the environment?


I use gcloud auth activate-service-account ... to login a service account to gcloud in a script. When the script is done, gcloud remains logged into that service account.

I prefer that gcloud remain logged in with my normal user account, so I can use it interactively.

How can I authenticate with a service account temporarily -- just within a single script execution?


Solution

  • Grant the Service Account Token Creator role to the "normal user account" and take advantage of the --impersonate-service-account = SERVICE_ACCOUNT_EMAIL flag for the gcloud commands you need to run within your script to avoid using the gcloud auth activate-service-account ... within your script at all or simply add the gcloud config set account ACCOUNT command at the end of your script in order to make sure that the normal user account is set after the script is done.