When working with Google Cloud Platform (GCP), service accounts are often used to grant programs and services access to cloud resources. These service accounts rely on cryptographic keys to authenticate, and those keys are as powerful as passwords. If someone gains access to a service account key, they can impersonate that service account—often with wide-reaching permissions across your infrastructure.
In this guide, we’ll cover how to handle service account keys safely in both local development and deployed environments, and what to do if a key is accidentally exposed.
1. Treat Service Account Keys Like Passwords
A service account key is essentially a password. Anyone who holds it can perform any action the account is authorized to do—whether that’s reading from a BigQuery dataset, running a Cloud Function, or adding files to a storage bucket.
Therefore:
Never commit service account keys to GitHub (even private repos).
Don’t email them, paste them in Slack, or transmit them in plaintext.
If you must share a key, use a secure, encrypted password manager.
2. Prefer GCP-Provided Authentication in Deployed Environments
The safest and easiest way to authenticate code running in GCP (e.g. Cloud Run, GKE, Compute Engine) is to attach a service account directly to the resource. GCP automatically makes credentials available through Application Default Credentials (ADC), and rotates them behind the scenes.
You don’t need to manage or hardcode any keys. In your code, just use the standard Google libraries and let GCP handle the rest.
from google.cloud import storage client = storage.Client() # uses ADC behind the scenes bucket = client.get_bucket("my-secure-bucket")
3. For Local Development, Use Environment Variables or Secret Manager
In local development, you might need to use a downloaded service account key. If so, don’t hardcode it in your codebase. Instead:
Store the key file securely.
Load it via the GOOGLE_APPLICATION_CREDENTIALS environment variable:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"
If you need to execute a GCP API call within CI/CD pipelines, inject the key via secure environment variables, or better yet, use Google Secret Manager to store and retrieve secrets securely at runtime.
4. What to Do If a Key Is Compromised
If you discover a key was accidentally exposed, such as being committed to a public repo, don’t panic, there are only a few easy steps you need to take;
1. Revoke the key immediately in the GCP console or via CLI:
gcloud iam service-accounts keys delete [KEY_ID] --iam-account [EMAIL]
2. Replace the key and distribute it securely if it’s still needed.
Have questions? Contact us at help@techallies.org!
Was this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article