google-cloud-platformgcloudgoogle-iamgoogle-cloud-iam

Google cloud: run app locally as service account whilst still running gcloud commands as my user


I am developing a cloud run service on google cloud and want to run it locally for testing using the service account I have configured cloud run to run the service as. My user has permission to impersonate the service account so to do this I am running

gcloud auth application-default login --impersonate-service-account

which works but now all the gcloud commands I run are as that service account as well!

Is there a way to run the app as a service account and gcloud as my regular user? In addition, what if I want to run multiple apps locally at the same time as different service accounts, is this possible? If it is relevant, I am using the official Go SDK for my app.

EDIT: I know this is possible with service account keys but I understand them to be bad practice so am looking for a way that doesn't use any long lived credentials.

I am coming from mostly AWS experience where I would achieve this by adding profiles to my ~/.aws/config or ~/.aws/credentials files and then specify the AWS_PROFILE environment variable when running the app and a different AWS_PROFILE when running commands using the CLI.

Thanks in advance for any help!


Solution

  • You can authenticate your regular user for gcloud commands using :

    gcloud auth login 
    

    The --impersonate-service-account flag for your service account only affects the application, not your gcloud CLI authentication context. It configures the application to use the service account, but gcloud will still be running as your regular user.

    To authenticate with a service account for the application, use:

    gcloud auth application-default login --impersonate-service-account=SERVICE_ACCOUNT_EMAIL
    

    As long as you haven't run the gcloud auth application-default login --impersonate-service-account command, gcloud commands will execute under your regular user account. If you've already run it, you can revoke the credentials with:

    gcloud auth application-default revoke 
    

    Yes, it is possible. To run multiple apps locally with different service accounts, you can use different terminal sessions or set different GOOGLE_APPLICATION_CREDENTIALS and auth activate-service-account for each app.