Google Cloud Functions - How to securely store service account private key when using Google Source Repository?

My solution when using cloud function with a service account is:

  1. Encrypt your service account credential json file using Cloud KMS/vault and upload it to Cloud Storage.
  2. Fetch service account credential json file from Cloud Storage and decrypt it using a Cloud KMS service account which has encrypt/decrypt permission.

  3. Parse service account credential json file at runtime and get private_key, client_email and projectId.

  4. Pass these three secret variables to the client library

We store config variables as environment variables for cloud function, they are plain text, but it's ok. Because they are not secret things.

We must not store secret things like plain text, e.g cloud function environment variables.


You can upload the service account file along with your functions and use it from within your code. It will remain secure there. Most developers will use a .gitignore or equivalent mechanism to keep that file from being added to source control. There is an example of loading service account credentials from Firebase samples. (If you're not using the Firebase SDK, you'll have to be mindful to convert the function definition to the Cloud style.

You could also use an env var, but you'll have to take special care in quoting and escaping the values to make sure they get to your function correctly. It's kind of a hassle, but doable.


As of January 2020, Google has released a Secret Manager, which is described as:

Secret Manager is a new Google Cloud service that provides a secure and convenient method for storing API keys, passwords, certificates, and other sensitive data. Secret Manager provides a central place and single source of truth to manage, access, and audit secrets across Google Cloud.

For Cloud Functions, there is a tutorial here on how to create a secret and then retrieve it from a cloud function.