Search code examples
pythongoogle-cloud-platformimpersonationservice-accounts

gcp - how to run Python application as Service Account without a key file


gcloud and gsutil have --impersonate-service-account by which we can impersonate a service account.

For Python program, is there a way to run the program as a service account without using the service account secret key file as key file is not recommended for security reason.

Service account keys could pose a security risk if compromised. We recommend that you avoid downloading service account keys


Solution

  • For Python program, is there a way to run the program as a service account without using the key file as key file is not recommended for security reason.

    If your Python program is running outside Google Cloud, then no, you must use credentials.

    You have a catch22. You need to be authorized using credentials to impersonate another credential.

    You have three choices:

    • user account credentials
    • another service account credentials
    • federated tokens

    Each of those methods requires secrets.

    For compute services, such as Compute Engine, Cloud Functions, Cloud Run, etc you can use the metadata service for authorization. However, then you do not need to impersonate credentials, you can just use the credentials as they are safe (no secrets stored on the machine).

    I wrote an article on this topic and how to setup impersonation using user account credentials:

    Google Cloud – Improving Security with Impersonation

    If impersonation is set up correctly, the flag --impersonate-service-account is not required.