Skip to content

05Identity and secretsService 5 of 13

Secret Managersecurity hardening

Harden Secret Manager: per-secret IAM, replication and CMEK, rotation with Pub/Sub, version destruction, audit logs and Cloud Run or GKE consumption.

Baseline
9 controls
Category
Identity and secrets
Updated
Reading
8 min read

Secret Manager stores API keys, database passwords, certificates and other credentials as versioned, IAM-protected, encrypted resources, and gives workloads a single audited place to read them from. The usual failures are not in the service itself but around it: database passwords pasted into Cloud Run or Cloud Functions environment variables where anyone with Viewer on the project can read them, roles/secretmanager.secretAccessor granted at project level so every service can read every secret, Data Access logs left off so nobody can say who read a credential after an incident, and secrets that are created once and never rotated. Treat Secret Manager as the only legitimate home for a secret, then make each secret readable by exactly one identity and every read visible.

Baseline controls

Apply these to every project that holds secrets, and keep production secrets in projects separate from the workloads that consume them where your team size allows it. CIS IDs refer to the CIS GCP Foundations Benchmark v5.0.1.

ControlWhyHow to checkCIS / SCC
Store secrets in Secret Manager, not environment variablesEnv vars are readable with Viewer-level accessgcloud run services describe SERVICE --format=yamlCIS 1.18, SECRETS_IN_ENVIRONMENT_VARIABLES
Grant Secret Accessor on the secret, not the projectLimits each identity to its own secretsgcloud secrets get-iam-policy SECRETn/a
Keep secret admins and secret readers separateAdmins should not read payloads by defaultIAM page, filter secretmanager rolesn/a
Pin replication to approved regionsData residency and blast radiusgcloud secrets describe SECRET --format="value(replication)"n/a
Encrypt sensitive secrets with CMEKLets you revoke access through the keygcloud secrets describe SECRETn/a
Set a rotation schedule with a Pub/Sub topicForces rotation to actually happengcloud secrets describe SECRET --format="value(rotation)"n/a
Delay version destructionRecover from accidental or malicious destroyversionDestroyTtl in secrets describen/a
Enable Data Access logs for Secret ManagerRecords every AccessSecretVersion callgcloud projects get-iam-policy PROJECT_ID --format="json(auditConfigs)"CIS 2.1
Include Secret Manager in a VPC SC perimeterStolen credentials cannot read from outsidegcloud access-context-manager perimeters describe PERIMETERCIS 3.8

Secrets belong in Secret Manager

An environment variable on a Cloud Run service or Cloud Run function is part of the resource configuration. It shows up in gcloud run services describe, in the console, in Cloud Asset Inventory exports, and to anyone with run.services.get, which roles/viewer includes. CIS 1.18 asks that secrets for functions live in Secret Manager instead. The same applies to Compute Engine metadata, Terraform state, container images and CI variables.

Create the secret without leaving the value in your shell history:

gcloud secrets create db-password \
  --project=prj-website-prod \
  --replication-policy=user-managed \
  --locations=europe-west1,europe-west4 \
  --labels=app=website,env=prod

printf '%s' "$(openssl rand -base64 32)" | \
  gcloud secrets versions add db-password --data-file=-

Security Command Center reports plaintext credentials in Cloud Run and Cloud Run functions environment variables as SECRETS_IN_ENVIRONMENT_VARIABLES once you enable the Sensitive Data Protection discovery for it, and secrets baked into Cloud Run container images as SECRETS_IN_CLOUD_RUN. See Cloud Run and Cloud Functions for moving existing env vars.

Console: Security > Secret Manager.

Per-secret IAM

Secret Manager roles, from most to least sensitive:

RoleCan do
roles/secretmanager.adminEverything, including reading payloads and changing IAM
roles/secretmanager.secretAccessorRead secret payloads (secretmanager.versions.access)
roles/secretmanager.secretVersionManagerAdd, enable, disable, destroy versions; no payload read
roles/secretmanager.secretVersionAdderAdd new versions only, useful for rotation jobs
roles/secretmanager.viewerMetadata only, no payload

Grant secretAccessor on the individual secret to the one runtime service account that needs it:

gcloud secrets add-iam-policy-binding db-password \
  --project=prj-website-prod \
  --member="serviceAccount:website-run@prj-website-prod.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor"

A project-level secretAccessor binding means a compromise of any service in the project yields every credential in it. If you must bind at project level (for a platform team's tooling, say), narrow it with an IAM condition on the secret name. Secret Manager resource names in conditions use the project number:

gcloud projects add-iam-policy-binding prj-website-prod \
  --member="serviceAccount:batch@prj-website-prod.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor" \
  --condition='expression=resource.name.startsWith("projects/PROJECT_NUMBER/secrets/batch-"),title=batch-secrets-only'

Remember that basic roles leak here too: roles/owner and roles/editor include secret payload access. Removing basic roles (see IAM) is a prerequisite for meaningful secret isolation. Rotation pipelines that only write new values should get secretVersionAdder, not admin.

Replication and CMEK

Every secret has a replication policy fixed at creation:

  • Automatic: Google chooses the regions. Simple, but you do not control where the payload lives.
  • User-managed: you list the regions. Use this when data residency matters, and pick at least two regions for availability.

Separately, regional secrets are created with --location and are stored and served from a single region through a regional endpoint. Use them for strict residency requirements; consuming services must support regional secrets, so check before migrating.

gcloud secrets create payment-api-key \
  --location=europe-west1 \
  --regional-kms-key-name=projects/prj-kms/locations/europe-west1/keyRings/secrets/cryptoKeys/payment

gcloud secrets versions access latest \
  --secret=payment-api-key --location=europe-west1

By default secrets are encrypted with Google-managed keys. With CMEK, Secret Manager wraps each version's data key with a Cloud KMS key you control, so disabling or destroying that key makes the payload unreadable. For automatic replication pass --kms-key-name (a global key); for user-managed replication each replica needs a key in its own region, set through a replication policy file:

{
  "userManaged": {
    "replicas": [
      {
        "location": "europe-west1",
        "customerManagedEncryption": {
          "kmsKeyName": "projects/prj-kms/locations/europe-west1/keyRings/secrets/cryptoKeys/sm"
        }
      },
      {
        "location": "europe-west4",
        "customerManagedEncryption": {
          "kmsKeyName": "projects/prj-kms/locations/europe-west4/keyRings/secrets/cryptoKeys/sm"
        }
      }
    ]
  }
}
gcloud secrets create db-password-cmek --replication-policy-file=replication.json

The Secret Manager service agent (service-PROJECT_NUMBER@gcp-sa-secretmanager.iam.gserviceaccount.com) needs roles/cloudkms.cryptoKeyEncrypterDecrypter on each key. Keep keys in a dedicated KMS project, as described on the Cloud KMS page. To make CMEK mandatory, add secretmanager.googleapis.com to the deny list of gcp.restrictNonCmekServices at the folder holding production.

Rotation, versions and expiration

Rotation schedules

Secret Manager does not change secret values for you. A rotation schedule publishes a SECRET_ROTATE message to Pub/Sub topics at the configured time, and your function or job generates the new credential, adds a version, and updates the backing system.

gcloud pubsub topics create secret-rotation --project=prj-website-prod

# Allow the Secret Manager service agent to publish
gcloud beta services identity create --service=secretmanager.googleapis.com --project=prj-website-prod
gcloud pubsub topics add-iam-policy-binding secret-rotation \
  --member="serviceAccount:service-PROJECT_NUMBER@gcp-sa-secretmanager.iam.gserviceaccount.com" \
  --role="roles/pubsub.publisher"

gcloud secrets update db-password \
  --topics=projects/prj-website-prod/topics/secret-rotation \
  --next-rotation-time="2026-12-01T00:00:00Z" \
  --rotation-period="2592000s"

The same topics also receive notifications for other secret events (new versions, destroy, delete), which makes them a useful audit trigger. Rotation is only real if consumers pick up the new version: reference latest in places that re-read the secret, or redeploy pinned consumers as part of the rotation job.

Versions and destroy

Versions are immutable. Disabling a version is reversible; destroying it deletes the payload permanently. Set a delayed destruction window so a destroy request first disables the version and only destroys it after the TTL, giving you time to notice a mistake or an attacker:

gcloud secrets update db-password --version-destroy-ttl=604800s

gcloud secrets versions disable 3 --secret=db-password
gcloud secrets versions destroy 3 --secret=db-password

Pin production consumers to a numbered version or alias when you need deterministic rollouts, and keep at most the current and previous versions enabled. Disable the previous one once every consumer has moved.

Expiration

--expire-time or --ttl deletes the whole secret automatically. Use it for temporary credentials (a contractor's integration, a migration password), never for long-lived production secrets, because expiry deletes every version irreversibly.

gcloud secrets create migration-temp-token --ttl=1209600s \
  --replication-policy=user-managed --locations=europe-west1

Network and perimeter controls

Secret Manager is supported by VPC Service Controls. Putting it inside the production perimeter means a stolen service account token used from outside the perimeter cannot read secrets, even with secretAccessor. Add secretmanager.googleapis.com to the restricted services of the perimeter that contains your production projects, and run it in dry-run mode first. Details on the VPC Service Controls page.

Workloads in a VPC should reach the API privately, through Private Google Access or a Private Service Connect endpoint for Google APIs (CIS 3.9), rather than over the internet.

Consuming secrets from Cloud Run and GKE

Cloud Run and Cloud Run functions

Cloud Run reads secrets at deploy or start time with the runtime service account's identity. Mount them as files or expose them as environment variables resolved from Secret Manager (the value is not stored in the service configuration):

gcloud run deploy website \
  --region=europe-west1 \
  --image=europe-docker.pkg.dev/prj-website-prod/app/website:1.4.2 \
  --service-account=website-run@prj-website-prod.iam.gserviceaccount.com \
  --set-secrets="DB_PASSWORD=db-password:5,/secrets/api/key=payment-api-key:latest"

An environment variable is resolved when the instance starts, so pin a version and redeploy on rotation. A mounted volume referencing latest is read when the file is read, so it picks up new versions without a redeploy. Code that calls the Secret Manager API directly should cache values briefly rather than calling AccessSecretVersion on every request.

GKE

On GKE, use the Secret Manager add-on (a managed Secrets Store CSI driver provider) with Workload Identity Federation for GKE instead of copying values into Kubernetes Secrets, which are only base64 encoded in etcd unless application-layer secrets encryption is on:

gcloud container clusters update prod-cluster \
  --location=europe-west1 --enable-secret-manager

gcloud secrets add-iam-policy-binding db-password \
  --role="roles/secretmanager.secretAccessor" \
  --member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/prj-website-prod.svc.id.goog/subject/ns/website/sa/website"
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: website-secrets
  namespace: website
spec:
  provider: gke
  parameters:
    secrets: |
      - resourceName: "projects/prj-website-prod/secrets/db-password/versions/5"
        path: "db-password"

The binding targets one Kubernetes service account in one namespace, so other workloads in the cluster cannot read the secret. More on the GKE page.

Logging and detection

Admin Activity logs (always on) record CreateSecret, UpdateSecret, DeleteSecret, AddSecretVersion, DisableSecretVersion, DestroySecretVersion and SetIamPolicy. Reading a payload, google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion, is a DATA_READ Data Access log and is off unless you enable it. Turn it on for secretmanager.googleapis.com at the organization (see Cloud Logging):

auditConfigs:
  - service: secretmanager.googleapis.com
    auditLogConfigs:
      - logType: DATA_READ
      - logType: ADMIN_READ

Alert on secret reads by principals other than the expected runtime service accounts. As a log-based metric filter:

protoPayload.serviceName="secretmanager.googleapis.com"
protoPayload.methodName="google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion"
protoPayload.authenticationInfo.principalEmail!~"-run@prj-website-prod\.iam\.gserviceaccount\.com$"

Also alert on:

  • SetIamPolicy on secrets or on projects that grants roles/secretmanager.secretAccessor or roles/secretmanager.admin;
  • DestroySecretVersion and DeleteSecret in production;
  • human principals (user:) reading production secrets outside a break-glass procedure;
  • bursts of AccessSecretVersion across many secrets by one identity, a typical sign of credential harvesting.

Common mistakes

  • Granting roles/secretmanager.secretAccessor at project level, so every service in the project can read every secret.
  • Moving a secret to Secret Manager but leaving the old plaintext environment variable on earlier Cloud Run revisions that still exist.
  • Enabling rotation notifications without a consumer for the topic, so the schedule fires and nothing rotates.
  • Pinning consumers to latest in environment variables and assuming a new version takes effect without a redeploy.
  • Leaving Data Access logs off, then being unable to say who read a leaked credential.
  • Using --ttl on production secrets and losing every version when it expires.
  • Forgetting that Owner and Editor include payload access, so secret-level IAM gives a false sense of isolation.

References

About the author

Security engineer writing practical, benchmark-aligned guides to hardening Google Cloud organizations, projects and workloads.

Related services

All services