Secret Manager in Google Cloud: The Digital Vault for Passwords, Keys and Tokens

Secret Manager in Google Cloud: The Digital Vault for Passwords, Keys and Tokens

A complete, plain-English guide to Secret Manager: how secrets and versions, replication, IAM, encryption, rotation, audit logging and integrations with Cloud Run, GKE, Cloud Build and other services work together to keep sensitive values out of your code and under your control.

Imagine a hotel with a hundred rooms. The hotel needs a master key, spare keys, the safe combination and the alarm code. Writing these on sticky notes and pinning them to the front desk would be a disaster, and so would giving every employee a copy of everything. Instead, the hotel keeps them in a locked, guarded vault. Only staff who need a specific key can sign for it, the vault keeps a record of every visit, and when a code is changed, the old one is retired and the new one takes its place. Modern applications have the same problem. They need database passwords, programming interface keys, tokens and certificates, and these secrets are too often pasted into code, configuration files or chat messages. Secret Manager is the digital vault Google Cloud provides to store them safely. In this guide we start from the first idea and build up to the design choices that keep secrets secret.

1What Is Secret Manager?

Before diving into settings, let us understand what counts as a secret and what problem a vault solves.

What is a secret?

A secret is any small piece of sensitive information that proves identity or grants access. Examples include database passwords, keys for outside programming interfaces, authentication tokens, private signing keys, certificates and encryption passphrases. If someone unauthorized learns a secret, they can act as your application, read your data or spend your money.

The one-sentence definition

Secret Manager is Google Cloud’s fully managed service for storing, accessing, managing and auditing secrets. It keeps each secret encrypted, controls who may read it with Identity and Access Management, records every access in audit logs and supports versions and rotation so secrets can be changed safely over time.

Simple Analogy

Think of a bank safe-deposit room. Each box holds something valuable. You need to be on the list for a particular box to open it, every visit is written in a ledger, and the bank can replace a box’s contents without moving the box. Secret Manager is the safe-deposit room, with each secret in its own box.

The problem it solves

Without a vault, secrets leak in predictable ways: committed into source code repositories, baked into container images, left in configuration files, pasted into chat tools, stored in plain environment files on developer laptops or copied into spreadsheets. Once a secret is copied into many places, you cannot know who has it, you cannot change it without hunting down every copy and you cannot prove who used it.

Encrypted
Secrets are encrypted at rest and in transit
Controlled
Access is granted per secret with IAM
Audited
Access can be logged and monitored
i
Good to Know

Secret Manager is designed for small sensitive values such as passwords and keys, not for large files or general configuration. Features, limits and pricing evolve, so confirm details in current Google Cloud documentation.

2Why Secrets Management Matters

Many of the most damaging security incidents begin with a leaked credential rather than a sophisticated attack.

Risk 1

Secrets in Source Code

Public and private repositories are scanned constantly by attackers looking for committed keys. A secret in history stays there even after deletion.

Risk 2

Secrets in Images and Files

Anyone who can pull an image or read a file can extract its secrets, often without noticing.

Risk 3

Shared and Never-Rotated Secrets

One password shared by many systems and left unchanged for years becomes impossible to retire safely.

Risk 4

No Audit Trail

When a secret leaks, you cannot tell who accessed it or when without logging.

Risk 5

Over-Broad Access

Too many people and services can read secrets they do not need, increasing the chance of leaks.

1

Hard-Coded Secrets

Passwords written directly into code. Fast to start, disastrous to maintain.

2

Configuration Files and Environment Variables

Secrets moved out of code but still stored in files copied around the organization.

3

Central Secret Store

Secrets live in one managed vault, fetched at runtime by authorized workloads.

4

Secretless Where Possible

Short-lived identities replace static secrets, and the vault holds only what truly must be a secret.

“A secret copied into ten places is no longer a secret; it is a rumor with a password.”

3Core Concepts and Vocabulary

A handful of terms appear in every Secret Manager conversation. Learn them once and the rest becomes easy.

Term 1

Secret

A named container with settings, such as labels, replication, rotation and permissions. It does not hold the sensitive value directly.

Term 2

Secret Version

One stored value of a secret. Each time you add a new value, a new version is created with its own number.

Term 3

Payload

The actual sensitive data inside a version, such as a password or key, limited to a small size.

Term 4

Version State

Whether a version is enabled, disabled or destroyed. Only enabled versions can be read.

Term 5

Latest Alias

A shortcut that points to the newest enabled version, convenient but with trade-offs we discuss later.

Term 6

Replication Policy

Where the secret’s data is stored: automatically across Google-chosen locations, or in regions you pick.

Term 7

Secret Accessor

The role that allows reading a secret’s payload, the most sensitive permission in the service.

Term 8

Rotation

The practice of replacing a secret’s value on a schedule or after a suspected leak.

Term 9

Labels and Annotations

Metadata you attach to secrets for organization, ownership and automation.

Term 10

Customer-Managed Encryption Key

An encryption key you control, used instead of Google-managed keys to protect secret data.

Simple Analogy

A secret is like a labeled safe-deposit box, and versions are the successive envelopes you place inside over time. The box keeps its label and lock rules, while the envelope inside changes when the password is changed. Old envelopes can be locked away or shredded.

flowchart TD
  P[Google Cloud Project] --> S[Secret: db-password]
  S --> V1[Version 1: Disabled]
  S --> V2[Version 2: Enabled]
  S --> V3[Version 3: Enabled, Latest]
  S --> M[Settings: Replication, Rotation, Labels, IAM]
        
FIG 1 — A secret holds settings and permissions; its values live in numbered versions

Versions are immutable

Once a version is created, its payload cannot be edited. To change a secret you add a new version. This design gives you a history, makes rollbacks possible and ensures that a reference to a specific version always returns exactly the same value until you disable or destroy it.

Version StateCan Be Read?Can Be Reversed?Typical Use
EnabledYesYes, can be disabledCurrent and still-supported values
DisabledNoYes, can be re-enabledRetired values kept briefly in case of rollback
DestroyedNo, payload is goneNo, permanent after any destruction delayValues that must never be used or recovered

4How Secret Manager Works Inside

Understanding the journey of a secret from creation to use shows where the protections apply.

Storing a secret

When you add a version, the service receives the payload over an encrypted connection, encrypts it before writing it to storage and stores it according to your replication policy. By default, the data is encrypted with keys managed by Google. If you choose customer-managed keys, the encryption uses a key in Cloud Key Management Service that you control, so revoking that key makes the secret unreadable.

Reading a secret

When a workload asks for a secret, it authenticates with its identity, usually a service account. The service checks IAM to confirm the identity holds permission to access that secret, decrypts the payload and returns it over an encrypted connection. The access is recorded in audit logs if data access logging is enabled.

1

Authenticate

The workload proves its identity using an attached service account or federated credentials.

2

Authorize

IAM checks whether that identity may access the specific secret or version.

3

Decrypt

The service decrypts the stored payload using the configured encryption key.

4

Return Securely

The payload is delivered over an encrypted channel to the workload.

5

Log the Access

If enabled, an audit entry records who accessed what and when.

sequenceDiagram
  participant W as Workload
  participant SM as Secret Manager
  participant IAM as IAM
  participant KMS as Encryption Key
  participant L as Audit Logs
  W->>SM: Access secret version with service account identity
  SM->>IAM: Does this identity have Secret Accessor?
  IAM-->>SM: Yes
  SM->>KMS: Decrypt payload
  KMS-->>SM: Plaintext payload
  SM-->>W: Secret value over encrypted channel
  SM->>L: Record access event
        
FIG 2 — Every read passes through identity, permission, decryption and logging
!
Common Mistake

Thinking that because secrets are encrypted in Secret Manager, they are safe once they reach your application. Once a workload reads a secret, it is in memory and can be printed in logs, sent in error messages or written to disk. Protecting secrets inside your code matters as much as protecting them in the vault.

5Replication, Locations and Regional Secrets

Where a secret’s data is stored affects availability, latency and compliance.

Automatic replication

With automatic replication, Google decides where to store the secret’s data and replicates it across locations for high availability. This is the simplest option and suits most cases where there are no strict rules about data location.

User-managed replication

With user-managed replication, you choose the specific regions where the secret is stored. This helps when regulations require data to stay in certain regions, or when you want the secret close to the workloads that use it. You can choose more than one region for resilience.

Regional secrets

Google Cloud has also introduced regional secrets, which are created and served within a single chosen region using regional endpoints. They suit strict data residency needs, because requests and storage stay in that region. Check the documentation for the current features and differences between global and regional secrets before choosing.

OptionWhere Data LivesBest For
Automatic replicationChosen and managed by Google across locationsSimplicity and high availability without location rules
User-managed replicationRegions you selectData residency or placement near workloads
Regional secretConfined to one region and its endpointsStrict regional isolation requirements
Simple Analogy

Automatic replication is like a bank that stores copies of your document in several secure vaults of its choosing. User-managed replication is telling the bank exactly which cities may hold copies. A regional secret is asking for the document to stay in a single vault in a single city.

i
Design Tip

A secret’s replication policy is set when it is created and generally cannot be changed afterwards. Decide your location needs first, because the usual fix is to create a new secret and migrate.

6Access Control with IAM

The strength of a vault depends on who holds the keys. Secret Manager uses IAM for fine-grained control.

The main roles

Role 1

Secret Manager Admin

Full control of secrets, versions and permissions. Keep to a very small group.

Role 2

Secret Manager Secret Accessor

Can read the payload of secret versions. Give to workloads that must use the secret, and to nobody else.

Role 3

Secret Manager Secret Version Adder

Can add new versions but not read existing values. Useful for rotation jobs.

Role 4

Secret Manager Secret Version Manager

Can disable, enable and destroy versions without reading payloads.

Role 5

Secret Manager Viewer

Can see metadata and list secrets but not read values.

Principles for granting access

1

Grant at the Secret Level

Give each workload access only to the specific secrets it needs, not to every secret in the project.

2

Use Dedicated Service Accounts

One service account per workload, so permissions and audit trails are clear.

3

Separate Reading from Managing

People who manage secrets should not automatically be able to read their values, and vice versa.

4

Add Conditions Where Useful

Use IAM conditions to limit access by time or by resource name patterns, for temporary needs.

5

Review Regularly

Check who can read which secrets and remove access that is no longer needed.

ANTI-PATTERN-01 Avoid
Problem

Granting the Secret Accessor role at the project or folder level to a broad group or a shared service account.

Why It’s Harmful

Everyone and every workload with that role can read every secret in scope, so one compromised account exposes all secrets.

Correct Approach

Grant Secret Accessor on individual secrets to specific service accounts, and keep human access to payloads rare and logged.

!
Common Mistake

Giving developers the Owner or Editor role “for convenience”, which can include the ability to read or change secrets. Basic roles are far broader than necessary. Use specific Secret Manager roles instead.

7Encryption and Key Management

Encryption is the lock on the vault door. Secret Manager offers choices about who holds the key.

Layer 1

Encryption in Transit

Requests and responses travel over encrypted connections, protecting values on the network.

Layer 2

Encryption at Rest with Google-Managed Keys

The default. Secrets are encrypted before being stored, and Google manages the keys.

Layer 3

Customer-Managed Encryption Keys

You supply a key from Cloud KMS. You control rotation and can disable it to make secret data unreadable.

Why Use Customer-Managed Keys

  • Meet policies requiring control of encryption keys
  • Ability to revoke access by disabling the key
  • Separate key administration from secret administration
  • Detailed audit trail of key use

Trade-offs to Consider

  • More components to configure and monitor
  • If a key is disabled or destroyed by mistake, secrets become unreadable
  • Key location must match secret location requirements
  • Additional cost for key use
Simple Analogy

With Google-managed keys, the bank locks your box with its own master key. With customer-managed keys, the bank locks your box with a lock that only works if you bring your own key. That gives you the power to make the contents inaccessible, and the responsibility not to lose your key.

i
Good to Know

Secret Manager and Cloud KMS solve different problems. Secret Manager stores and delivers secret values. Cloud KMS manages cryptographic keys and performs encryption operations. Applications typically use Secret Manager for passwords and tokens, and KMS for encrypting data or signing, though KMS can also protect the secrets inside Secret Manager.

8Versions, Rotation and Expiration

A secret that never changes becomes a liability. Secret Manager helps you change secrets safely.

Why rotate secrets?

Rotation limits how long a leaked secret stays useful. If a password is changed every ninety days, a stolen copy from six months ago is already worthless. Rotation also forces your systems to prove they can handle secret changes without outages, which is valuable practice before a real emergency.

How rotation works in Secret Manager

Secret Manager does not itself change passwords in your databases or programming interfaces. Instead, you set a rotation schedule on a secret, and when the time arrives, the service publishes a notification to a Pub/Sub topic. A function or automation listening to that topic generates a new credential in the target system, adds it as a new version of the secret and, after confirming everything works, disables the old version.

sequenceDiagram
  participant SM as Secret Manager
  participant PS as Pub/Sub Topic
  participant R as Rotation Function
  participant DB as Target System
  SM->>PS: Rotation due notification
  PS->>R: Trigger rotation
  R->>DB: Create new credential
  R->>SM: Add new secret version
  R->>DB: Verify new credential works
  R->>SM: Disable old version later
        
FIG 3 — Secret Manager signals when rotation is due; your automation performs the rotation

A safe rotation pattern

1

Create the New Credential

Generate a new password or key in the target system while the old one still works.

2

Add a New Version

Store the new value as the newest version of the secret.

3

Let Workloads Pick It Up

Applications fetch the new value on restart or refresh, and keep working throughout.

4

Verify and Retire the Old Credential

Confirm no one uses the old value, then remove it from the target system.

5

Disable, Then Destroy the Old Version

Disable first as a safety net, and destroy after a waiting period if no problems appear.

Expiration and delayed destruction

Feature 1

Expiration Time or Lifetime

A secret can be set to expire and be deleted automatically, useful for temporary credentials.

Feature 2

Delayed Version Destruction

A waiting period before a destroyed version is permanently erased, allowing recovery from mistakes.

Feature 3

Rotation Notifications

Scheduled events published to Pub/Sub so automation can act at the right time.

!
Common Mistake

Destroying the old version immediately after adding a new one, before all workloads have switched. Applications that pinned the old version or cached it will fail. Disable first, watch for errors, and destroy only after a safe waiting period.

9Pinning Versions Versus Using Latest

One of the most common design questions is whether an application should ask for a specific version or for the newest one.

ApproachHow It WorksStrengthWeakness
Pin a specific versionThe application always requests, for example, version 3Predictable and repeatable; no surprise changesYou must update the reference to adopt a new version
Use the latest aliasThe application requests the newest enabled versionPicks up rotations automaticallyA bad new version affects everyone at once, and rollbacks need care

Choosing between them

For secrets that change often and where your application can handle changes smoothly, using the latest alias reduces manual work. For critical systems where you want controlled rollouts and easy rollback, pinning versions and updating the reference as part of a deployment gives more control. Many teams pin versions in production and use latest in development.

Simple Analogy

Using “latest” is like telling a driver to always take the newest map from the glovebox. Convenient, but if someone puts a wrong map there, every driver is misled. Pinning is giving each driver a specific numbered map, so you decide when everyone switches.

ANTI-PATTERN-02 Avoid
Problem

Using the latest alias everywhere, while rotation automation adds new versions without testing them against live systems.

Why It’s Harmful

A faulty new value instantly reaches every consumer, causing outages that are hard to trace because the reference never changed.

Correct Approach

Test new versions before enabling them for production, pin versions for critical workloads and move references deliberately, or stage rollouts.

i
Practical Insight

Applications that read a secret only at startup will not notice a rotation until they restart. Design workloads to refresh secrets periodically or on failure, so rotations do not require emergency restarts.

10Using Secrets from Your Workloads

A vault is only useful if your applications can get secrets easily and safely. Google Cloud services offer several ways.

Platform 1

Cloud Run

Secrets can be exposed to a service as environment variables or mounted as files in a volume, with the service’s identity controlling access.

Platform 2

Cloud Functions

Functions can reference secrets as environment variables or mounted files in a similar way.

Platform 3

Google Kubernetes Engine

Secrets can be delivered to pods through integrations such as a secrets store driver, or fetched by applications using workload identity.

Platform 4

Compute Engine

Applications on virtual machines fetch secrets using client libraries or the API with the machine’s service account.

Platform 5

Cloud Build

Build steps can access secrets at build time without placing them in the build configuration or logs.

Platform 6

Other Systems

Any application, inside or outside Google Cloud, can use the API with proper credentials, including through federation.

Three delivery styles

StyleHow the App Gets the SecretConsiderations
Fetch through the API or client libraryThe code requests the secret when neededMost flexible; supports refresh; requires code changes
Mounted file or volumeThe platform places the secret as a file the app readsNo code change to the vault; can pick up new versions for the latest alias; avoids exposure through process environment
Environment variableThe platform injects the value into the process environment at startSimple; value fixed at start; can leak through diagnostics or child processes
flowchart LR
  SM[Secret Manager] --> CR[Cloud Run Service]
  SM --> GKE[GKE Pods]
  SM --> VM[Compute Engine Application]
  SM --> CB[Cloud Build Step]
  CR --> APP1[Application Uses Secret in Memory]
  GKE --> APP2[Application Uses Secret in Memory]
        
FIG 4 — Many Google Cloud platforms can fetch or mount secrets using their own service identity
Simple Analogy

An environment variable is like writing the combination on a note that the worker carries all day. A mounted file is like placing a locked envelope on the worker’s desk that they open when needed. Fetching through the API is like calling the vault each time and getting a fresh answer.

!
Common Mistake

Printing environment variables or full configuration into logs during debugging. Secrets injected as environment variables are easily dumped by diagnostic tools and error reports. Never log secrets, and prefer file-based delivery for high-value secrets when your platform supports it.

11Audit Logging and Monitoring

A vault without a visitor log is only half a vault. Secret Manager integrates with Cloud Audit Logs.

What gets logged

Log 1

Admin Activity

Creating, changing or deleting secrets and permissions. Recorded by default.

Log 2

Data Access

Reading secret payloads and listing secrets. Must be enabled, and can be high volume for busy applications.

Enabling data access logs for Secret Manager is strongly recommended for sensitive environments, because it answers the key question after any incident: who read this secret and when? Because logs can be large for chatty workloads, plan for the volume and storage cost.

What to alert on

EventWhy It Matters
Access by an unexpected identityMay indicate stolen credentials or misconfiguration
Spike in access volumeCould mean a scraping attempt or a looping application
Permission changes on secretsSomeone may be widening access to read values
Destruction or disabling of versionsMay cause outages, or be an attempt to hide evidence
Access from unusual locations or at unusual timesPotential sign of misuse
Failed access attemptsPossible probing for secrets
1

Enable Data Access Logs

Turn on logging for Secret Manager at the appropriate level.

2

Route Logs Centrally

Send them to a protected, central location with controlled retention.

3

Create Alerts

Build log-based alerts for the high-risk events above.

4

Review and Tune

Check which identities legitimately read which secrets and refine alerts to reduce noise.

i
Design Tip

Audit logs record that a secret was accessed, not the secret itself. Never rely on logs to store values, and never log the payload in your own application either.

12Network and Perimeter Security

Besides identity checks, you can limit where secret access requests can come from.

Control 1

Private Google Access

Workloads without public addresses can reach Secret Manager over Google’s network.

Control 2

Private Service Connect

Use a private endpoint address in your own network to reach Google APIs, including Secret Manager.

Control 3

VPC Service Controls

Define a perimeter that restricts Secret Manager access to approved projects and networks, reducing the risk of exfiltration with stolen credentials.

Control 4

Organization Policies

Enforce rules such as allowed locations for secrets or customer-managed key requirements.

Simple Analogy

IAM checks that the person at the vault door is on the list. A service perimeter is a fence around the whole building that only lets listed people in from approved roads. Even a valid key holder is stopped if they approach from an unapproved direction.

!
Common Mistake

Enabling a perimeter without testing and then blocking build pipelines or monitoring tools that legitimately read secrets from outside. Start in dry-run mode, review what would be blocked and add the necessary access levels before enforcing.

13Secretless Alternatives: Do You Need a Secret at All?

The best secret is the one you never have to store. Many modern designs avoid static secrets for access to Google Cloud itself.

Prefer identity over secrets where possible

When one Google Cloud service calls another, you do not need a password or key. The calling workload uses its attached service account and receives short-lived tokens automatically, with IAM deciding what it may do. External workloads can use workload identity federation to exchange their own identity for a short-lived Google Cloud token. Secret Manager is best reserved for credentials that cannot be replaced by identity, such as third-party programming interface keys, database passwords and signing secrets.

SituationBetter ChoiceWhy
One Google Cloud service calling anotherAttached service accountNo secret to store or rotate
Outside pipeline calling Google CloudWorkload identity federationShort-lived tokens without keys
Connecting to a managed databaseIdentity-based database login where supportedAvoids a static password
Calling a third-party service with an API keySecret ManagerThe key must exist; vault protects it
Application needing a private signing keyCloud KMS signing or Secret ManagerKMS can sign without exposing the key
Non-sensitive settingsConfiguration service or environment settingsNo need to pay for vault protection
flowchart TD
  Q1{Does the app need to prove identity to Google Cloud?} -->|Yes| A1[Use a service account or federation, no secret needed]
  Q1 -->|No| Q2{Is the value sensitive?}
  Q2 -->|No| A2[Use normal configuration]
  Q2 -->|Yes| Q3{Can the operation be done by KMS without exposing the key?}
  Q3 -->|Yes| A3[Use Cloud KMS]
  Q3 -->|No| A4[Store in Secret Manager]
        
FIG 5 — A simple guide to when a secret in the vault is really needed

14Secret Manager Compared with Other Options

Several places can hold sensitive values. Knowing the differences helps you choose.

OptionWhat It IsBest FitLimitations
Secret ManagerManaged vault for secrets with versions, IAM and auditPasswords, tokens and keys used by applicationsSmall payloads; not a general configuration store
Cloud KMSManaged cryptographic key serviceEncryption, decryption and signing without exposing keysNot meant for storing arbitrary secret values
Environment variables in code or configurationValues set in plain settingsNon-sensitive configurationVisible to anyone with access to the configuration; no audit or rotation
Source code or config filesValues written into repositoriesNothing sensitiveLeaks through history and copies
Cloud Storage objectsGeneral object storageLarge files and non-sensitive dataNo secret-specific versioning, rotation or access patterns
Self-hosted secret managersSoftware you run yourselfMulticloud strategies or special featuresYou operate, secure and scale it
Configuration and parameter servicesStores for application settingsNon-secret settings with versionsNot designed for protecting sensitive values
Simple Analogy

A bulletin board is fine for the office lunch menu, but not for the safe combination. KMS is a machine that opens locks on your behalf without ever showing the key. Secret Manager is the safe where you keep the combination itself, with a visitor log.

i
Good to Know

Google Cloud has been adding services for application configuration alongside Secret Manager. Keep sensitive values in the vault and non-sensitive settings in a configuration service, so you do not pay vault-level handling for ordinary parameters. Check current documentation for the latest options.

15Organizing Secrets at Scale

A few secrets are easy to manage. Hundreds across many teams need structure.

Naming and labeling

Choose a clear naming standard that includes the application, environment and purpose, such as “payments-prod-database-password”. Add labels for owner, environment, data sensitivity and rotation policy. Good naming and labels make access reviews, cost analysis and incident response much faster.

Project strategy

Strategy 1

Secrets Alongside Each Application

Each application’s project holds its own secrets. Simple permissions and clear ownership, but more places to manage.

Strategy 2

Central Secrets Project

A dedicated, tightly controlled project holds secrets for many applications. Central governance, but requires careful per-secret permissions.

Strategy 3

Per-Environment Separation

Development, testing and production secrets live in separate projects, so a development mistake cannot touch production values.

Provisioning with infrastructure as code

Define secrets, their settings and permissions in version-controlled infrastructure configuration, but keep the secret values themselves out of that code. Create the secret containers through automation and add the values through a secure process, such as a rotation job or a one-time controlled entry by an authorized person.

1

Define the Secret Container as Code

Name, labels, replication, rotation settings and permissions are reviewed in version control.

2

Populate the Value Securely

A trusted process or person adds the first version outside of code.

3

Grant Per-Secret Access

The workload’s service account receives Secret Accessor on that secret only.

4

Monitor and Review

Audit logs and periodic reviews confirm that access matches intent.

ANTI-PATTERN-03 Avoid
Problem

Putting the actual secret values into infrastructure-as-code files or variable files stored in repositories.

Why It’s Harmful

The values end up in version history, state files and build logs, defeating the purpose of the vault.

Correct Approach

Manage the secret containers and permissions as code, and supply values through a separate secure path or generated automation.

16Performance, Caching and Reliability

Secret Manager is built for reliability, but how your application uses it affects speed, cost and resilience.

Avoid asking on every request

Fetching a secret from the API takes a network call. If your application fetches the same secret on every user request, you add delay, increase cost and risk hitting request quotas. Instead, read the secret once at startup or periodically, keep it in memory and refresh it on a schedule or when authentication fails.

Plan for outages and quotas

Practice 1

Cache in Memory Only

Keep values in process memory, never written to disk or logs, and clear them when no longer needed.

Practice 2

Retry with Backoff

Handle brief errors by retrying with increasing delays rather than hammering the service.

Practice 3

Fail Safe at Startup

Decide whether a workload should refuse to start or run degraded if secrets cannot be fetched.

Practice 4

Mind Quotas

Large fleets starting at once can generate bursts of reads. Stagger rollouts and check current quotas.

Practice 5

Replicate for Availability

Use replication that matches your availability needs, especially for multi-region applications.

!
Common Mistake

Fetching secrets during every request in a high-traffic service, then being surprised by bills, latency and quota errors. Cache in memory with a sensible refresh period.

17Cost and Pricing

Secret Manager costs are usually small, but they scale with the number of versions and the volume of access.

Cost 1

Active Secret Versions

Billed per active version per month, and per replica location. Keeping many old enabled versions adds up.

Cost 2

Access Operations

Billed per set of access requests. Applications that fetch secrets on every request can create large volumes.

Cost 3

Rotation Notifications

Each rotation event published may have a charge.

Cost 4

Audit Logging Volume

Data access logs for busy workloads can create meaningful logging costs.

Cost 5

Key Management Costs

Customer-managed keys add costs for key versions and cryptographic operations.

Ways to manage cost

Good Habits

  • Disable and then destroy old versions you no longer need
  • Cache secrets in memory and refresh on a schedule
  • Replicate only to the regions you need
  • Keep non-sensitive settings out of the vault
  • Tune data access logging to what you truly need
  • Check pricing and free allowances periodically

Cost Traps

  • Fetching secrets on every request
  • Leaving dozens of old versions enabled
  • Replicating everywhere by default
  • Storing every config value as a secret
  • Unbounded data access logs sent to expensive storage
i
Important

Pricing details, units and free allowances change over time. Always confirm current rates on the official Secret Manager pricing page before planning a budget. Compared with the cost of a leaked credential, the service is usually inexpensive.

18Incident Response: When a Secret Leaks

Even good teams sometimes leak secrets. A prepared response limits the damage.

1

Assume It Is Compromised

Treat any secret that was exposed as stolen, even if you see no evidence of misuse yet.

2

Create a New Credential

Generate a replacement in the target system and add it as a new secret version.

3

Switch Workloads to the New Value

Restart or refresh workloads so they use the new version.

4

Revoke the Old Credential

Invalidate the leaked value in the target system, and disable and later destroy the old version.

5

Investigate with Logs

Use audit logs and the target system’s logs to see whether the leaked value was used and by whom.

6

Fix the Root Cause

Find how it leaked, remove it from repositories, images and chats and add controls to prevent a repeat.

!
Common Mistake

Deleting the leaked secret from a repository and assuming the problem is solved. Version history, forks, caches and clones keep copies. The only safe response is to rotate the credential and revoke the old one.

Prevention 1

Secret Scanning in Pipelines

Scan code and images for committed secrets before they are merged or published.

Prevention 2

Pre-Commit Checks

Block commits containing secret-like strings on developer machines.

Prevention 3

Short-Lived Credentials

Prefer credentials that expire quickly, limiting the usefulness of leaks.

Prevention 4

Practice the Drill

Rehearse rotation so it is fast and safe in a real emergency.

19Design Patterns and Anti-patterns

Patterns capture what experienced teams repeatedly find works; anti-patterns capture what goes wrong.

Helpful patterns

One Secret per Purpose, One Account per Workload

Each secret has a single clear purpose and owner, and each workload has its own service account with access only to the secrets it needs.

Automated Rotation with Staged Rollout

Rotation functions create the new credential, add a version, verify it with a test and only then retire the old one, with workloads refreshing without downtime.

Environment Isolation

Separate projects for development, testing and production with different permissions and no shared secret values between environments.

Mounted Secrets for Sensitive Values

High-value secrets are delivered as mounted files rather than environment variables, reducing accidental exposure through diagnostics.

Audit-Driven Access Reviews

Data access logs show which identities actually read each secret. Reviews remove access that is never used.

Identity First, Secrets Second

Teams use service accounts and federation wherever possible, and reserve the vault for credentials that truly cannot be replaced by identity.

Anti-patterns to avoid

ANTI-PATTERN-04 Avoid
Problem

Using the same secret value across development, testing and production, or across many applications.

Why It’s Harmful

A leak in a low-security environment exposes production, and rotating the value requires updating everything at once.

Correct Approach

Use distinct values per environment and per application, so exposure and rotation stay contained.

ANTI-PATTERN-05 Avoid
Problem

Storing downloaded service account keys as secrets and calling it secure.

Why It’s Harmful

You still have long-lived keys that can be copied once read, and they bypass the benefits of short-lived identities.

Correct Approach

Use attached service accounts, impersonation and workload identity federation so no long-lived key exists.

ANTI-PATTERN-06 Avoid
Problem

Sharing secret values through chat messages, emails or tickets so that new team members can get set up.

Why It’s Harmful

Messages are retained, searchable and copied. Secrets spread to places no one controls.

Correct Approach

Grant new people or services access through IAM, so they retrieve values from the vault with their own identity.

20Advantages, Disadvantages and Real-World Uses

An honest view of strengths, limits and where teams actually use Secret Manager.

Advantages

  • Fully managed, with no vault servers to build or patch
  • Versioning, rotation notifications and delayed destruction
  • Fine-grained IAM at the secret level
  • Encryption by default, with customer-managed key options
  • Audit logging and integration with perimeters
  • Native integration with Cloud Run, Functions, GKE and Cloud Build
  • Low cost relative to the protection it provides

Disadvantages / Trade-offs

  • Rotation automation is yours to build, since the service only sends notifications
  • Small payload limits, so not suitable for large files
  • Replication policy is generally fixed at creation
  • Data access logging adds volume and cost
  • Applications must be designed to refresh secrets
  • Misconfigured access can still expose everything it protects

Real-world examples

Web Application with a Database

A Cloud Run service reads its database password from a mounted secret. Rotation runs every ninety days through a function triggered by a notification, and the service picks up the new value without downtime.

Payment Integration

An online shop stores its payment provider’s API key in Secret Manager with a customer-managed key, tightly limited access, data access logging and alerts on any unexpected reader.

Build Pipeline

A build pipeline fetches a package registry token during a build step only, never stores it in configuration and never prints it, leaving an auditable record of each access.

Kubernetes Platform

A platform team delivers secrets to pods through a secrets integration, each application using its own workload identity so one pod cannot read another’s secrets.

Regulated Industry

A healthcare firm uses regional secrets and customer-managed keys to meet data residency rules, with perimeter controls and centralized logging for audits.

21Best Practices and Frequently Asked Questions

A checklist to carry into every project, followed by answers to common beginner questions.

Best Practices

  • Never store secrets in code, images, chat tools or plain configuration
  • Prefer identity-based access and use the vault only for credentials that must exist
  • Grant Secret Accessor per secret to dedicated service accounts
  • Separate secrets by environment and application
  • Rotate on a schedule and rehearse emergency rotation
  • Pin versions for critical workloads and test before enabling new ones
  • Disable, then destroy, old versions after a safe delay
  • Enable data access logs and alert on unusual access
  • Cache in memory, never log secrets and prefer mounted files for sensitive values
  • Use perimeters and private access where appropriate

Common Mistakes

  • Granting accessor roles at project level to many identities
  • Using one value everywhere
  • Treating encryption in the vault as protection inside the app
  • Destroying old versions too soon
  • Fetching on every request
  • Logging environment variables
  • Putting secret values in infrastructure code
  • Leaving data access logging off
Q1What is the difference between a secret and a secret version?

A secret is the named container with settings and permissions. A secret version holds an actual value. You add new versions to change the value, and each version is immutable.

Q2Can I edit an existing secret value?

No. Versions cannot be edited. You add a new version with the new value and then disable or destroy older versions as appropriate.

Q3Does Secret Manager rotate my database password for me?

Not by itself. It can notify your automation when rotation is due through Pub/Sub. Your function or workflow creates the new credential and adds it as a new version.

Q4Should I use the latest alias or a pinned version?

Use latest where automatic pickup of rotations is valuable and your application can handle changes safely. Pin versions for critical systems where you want controlled rollouts and easy rollbacks.

Q5Who should be allowed to read secrets?

Only the specific workloads that need each secret, through dedicated service accounts with the Secret Accessor role on that secret. Human access to payloads should be rare, justified and logged.

Q6Are secrets encrypted?

Yes. They are encrypted in transit and at rest by default. You can also use customer-managed encryption keys if your policies require control over keys.

Q7How do I use a secret in Cloud Run or GKE?

Cloud Run can expose a secret as an environment variable or a mounted file, and GKE can deliver secrets through integrations or fetch them using workload identity. Check current documentation for the options.

Q8Do I need Secret Manager for calls between Google Cloud services?

Usually not. Use attached service accounts and IAM, which provide short-lived credentials without storing any secret.

Q9What is the difference between Secret Manager and Cloud KMS?

Secret Manager stores and delivers secret values such as passwords and tokens. Cloud KMS manages cryptographic keys and performs encryption and signing without exposing the key itself.

Q10How do I know who read a secret?

Enable data access audit logs for Secret Manager. They record which identity accessed which secret and when, though they never record the secret value.

Q11Can I recover a destroyed version?

Not after destruction completes. If you configured a delayed destruction period, you may be able to recover during the delay. Disable versions first and destroy only when sure.

Q12What should I do if a secret leaks?

Treat it as compromised: create a new credential, add it as a new version, switch workloads, revoke the old credential, review logs and fix the cause. Removing it from a repository is not enough.

22Summary and Key Takeaways

Secret Manager is Google Cloud’s managed vault for sensitive values such as passwords, tokens and keys. Each secret is a named container with its own settings and permissions, while the values live in immutable, numbered versions that can be enabled, disabled or destroyed. Encryption, IAM at the secret level, audit logging, perimeters and customer-managed keys protect them, while replication and regional options address availability and residency. Rotation is supported through scheduled notifications that drive your own automation, and workloads on Cloud Run, Functions, GKE, Compute Engine and Cloud Build can read secrets using their own identities. The strongest designs combine the vault with habits outside it: use identity instead of secrets wherever possible, grant narrow access, separate environments, cache carefully, never log secrets and practice rotation before an emergency. Because features, limits and prices change, confirm specifics in current Google Cloud documentation.

Key Takeaways

  • A vault, not a notebook — keep passwords, tokens and keys in Secret Manager instead of code, images, chats or plain configuration files.
  • Secrets hold settings, versions hold values — versions are immutable, so change a secret by adding a new version and retire old ones by disabling and then destroying them.
  • Grant narrowly — give Secret Accessor per secret to dedicated service accounts, separate reading from managing and avoid broad project-level grants.
  • Rotate by design — use rotation schedules and notifications to drive automation, pin or test versions for critical systems and let workloads refresh secrets safely.
  • Prefer identity over secrets — use service accounts and federation for access to Google Cloud, and reserve the vault for credentials that must exist.
  • Protect, log and watch — use encryption choices, perimeters and private access, enable data access logs and alert on unusual reads or permission changes.
  • Handle values carefully in code — cache in memory, never log or print secrets, prefer mounted files for sensitive values and rehearse your response to a leak.