Secret Manager

Google Cloud · Practical · 10 min

Secrets in environment files, images or Git leak; Secret Manager gives versioning, IAM and audit logs instead.

Secret Manager stores small sensitive values (up to 64 KiB) as secrets with immutable versions. Adding a new value creates version 2; the alias latest points to the newest enabled version. Versions can be disabled (reversible) or destroyed (permanent).

Access control is per secret: grant roles/secretmanager.secretAccessor on that secret to the service account that needs it, not on the whole project. Every access is recorded in Data Access audit logs if you enable them.

Ways to consume a secret:

  • Cloud Run / Cloud Run functions: --set-secrets=ENV_VAR=secret:version exposes it as an environment variable, or /path=secret:latest mounts it as a file. Mounted latest picks up new versions on read; environment variables are resolved at instance start.
  • Client library: access_secret_version("projects/P/secrets/S/versions/latest").
  • GKE: the Secret Manager add-on (CSI driver) mounts secrets as files.

Pin a specific version (e.g. :3) in production so a rotation is a deliberate deploy, or use latest with file mounts if the app re-reads it. Use rotation schedules, which publish notifications to Pub/Sub so your code can rotate the value. Replication is automatic (Google-chosen regions) or user-managed when data residency matters; regional secrets are also available.

Example

printf 's3cr3t-p4ss' | gcloud secrets create db-pass --data-file=- --replication-policy=automatic
printf 'n3w-p4ss' | gcloud secrets versions add db-pass --data-file=-   # version 2

gcloud secrets add-iam-policy-binding db-pass \
  --member="serviceAccount:orders-api@shop-dev-4821.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor"

gcloud secrets versions access latest --secret=db-pass     # n3w-p4ss

# Env var pinned to version 2, plus a file mount that follows latest
gcloud run services update orders-api --region=europe-west1 \
  --set-secrets=DB_PASS=db-pass:2,/secrets/api-key=api-key:latest

Remember

  • Secrets have immutable versions; latest is an alias
  • Grant secretAccessor on individual secrets
  • Cloud Run can inject secrets as env vars or files

Watch out for

  • Passing a secret with --set-env-vars, which stores it in plain text in the service config.

Check yourself

  1. You add a new version of a secret used as DB_PASS=db-pass:latest env var in Cloud Run. When does the service see it?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: cloud.google.com/secret-manager/docs/overview