google-cloud-platformgcloudgoogle-cloud-sqlcloud-sql-proxy

Is there a way to impersonate a service account with the cloudsql_proxy executable?


https://github.com/GoogleCloudPlatform/cloudsql-proxy

I have found this is possible by setting impersonation system wide with this command: gcloud config set auth/impersonate_service_account <MY_SERVICE_ACCOUNT>.

The proxy exe seems to read the gcloud config.

But that is really clunky. I want to start the proxy and specify a specific user to impersonate without having to change it system wide. Also, I'm not resorting to generating non-expiring json keys- I want to use impersonation.

Many Gcloud commands now support a specific switch for this, but the proxy exe does not. See this GitHub issue (with no response from google): https://github.com/GoogleCloudPlatform/cloudsql-proxy/issues/417

Can I run gcloud auth print-access-token --impersonate-service-account=<MY_SERVICE_ACCOUNT> and set an env var the proxy exe will pick up or something?

I can't find anything in the code except this mention of gcloud: https://github.com/GoogleCloudPlatform/cloudsql-proxy/blob/eca37935e7cd54efcd612c170e46f45c1d8e3556/cmd/cloud_sql_proxy/cloud_sql_proxy.go#L160

  • When the gcloud command-line tool is installed on the local machine, the "active account" is used for authentication. Run 'gcloud auth list' to see which accounts are installed on your local machine and 'gcloud config list account' to view the active account.

which is funny because when running auth/impersonate_service_account gcloud config list account doesn't say anything about it.

Is there a way to have Gcloud do impersonation on a per session basis?

EDIT: just to follow up, per the answer the --token totally works, so now I can run the proxy with IAM auth and impersonation a gsa simultaneously:

# start proxy with IAM login as a GSA with a cloud sql service account setup
./cloud_sql_proxy \
    -enable_iam_login \
    -dir=/var/run/cloudsql \
    -instances=project_id:region:instance_name \
    --token=$(gcloud auth print-access-token --impersonate-service-account='my-gsa@myco.iam.gserviceaccount.com')

# now can auth through proxy as cloud sql federated user 
psql "sslmode=disable \
    host='/var/run/cloudsql/project_id:region:instance_name' \
    user=my-gsa@myco.iam dbname=mydb"

Solution

  • Newer versions of Cloud SQL Proxy (≥ 2.0) have explicit support for impersonation, so things now work a bit differently from the previous answers:

    cloud-sql-proxy --impersonate-service-account=<service-account> <instance-connection-name>
    

    or if you prefer:

    CSQL_PROXY_IMPERSONATE_SERVICE_ACCOUNT=<service-account> cloud-sql-proxy <instance-connection-name>