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.
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.
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.
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.
Secrets in Images and Files
Anyone who can pull an image or read a file can extract its secrets, often without noticing.
Shared and Never-Rotated Secrets
One password shared by many systems and left unchanged for years becomes impossible to retire safely.
No Audit Trail
When a secret leaks, you cannot tell who accessed it or when without logging.
Over-Broad Access
Too many people and services can read secrets they do not need, increasing the chance of leaks.
Hard-Coded Secrets
Passwords written directly into code. Fast to start, disastrous to maintain.
Configuration Files and Environment Variables
Secrets moved out of code but still stored in files copied around the organization.
Central Secret Store
Secrets live in one managed vault, fetched at runtime by authorized workloads.
Secretless Where Possible
Short-lived identities replace static secrets, and the vault holds only what truly must be a secret.
3Core Concepts and Vocabulary
A handful of terms appear in every Secret Manager conversation. Learn them once and the rest becomes easy.
Secret
A named container with settings, such as labels, replication, rotation and permissions. It does not hold the sensitive value directly.
Secret Version
One stored value of a secret. Each time you add a new value, a new version is created with its own number.
Payload
The actual sensitive data inside a version, such as a password or key, limited to a small size.
Version State
Whether a version is enabled, disabled or destroyed. Only enabled versions can be read.
Latest Alias
A shortcut that points to the newest enabled version, convenient but with trade-offs we discuss later.
Replication Policy
Where the secret’s data is stored: automatically across Google-chosen locations, or in regions you pick.
Secret Accessor
The role that allows reading a secret’s payload, the most sensitive permission in the service.
Rotation
The practice of replacing a secret’s value on a schedule or after a suspected leak.
Labels and Annotations
Metadata you attach to secrets for organization, ownership and automation.
Customer-Managed Encryption Key
An encryption key you control, used instead of Google-managed keys to protect secret data.
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]
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 State | Can Be Read? | Can Be Reversed? | Typical Use |
|---|---|---|---|
| Enabled | Yes | Yes, can be disabled | Current and still-supported values |
| Disabled | No | Yes, can be re-enabled | Retired values kept briefly in case of rollback |
| Destroyed | No, payload is gone | No, permanent after any destruction delay | Values 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.
Authenticate
The workload proves its identity using an attached service account or federated credentials.
Authorize
IAM checks whether that identity may access the specific secret or version.
Decrypt
The service decrypts the stored payload using the configured encryption key.
Return Securely
The payload is delivered over an encrypted channel to the workload.
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
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.
| Option | Where Data Lives | Best For |
|---|---|---|
| Automatic replication | Chosen and managed by Google across locations | Simplicity and high availability without location rules |
| User-managed replication | Regions you select | Data residency or placement near workloads |
| Regional secret | Confined to one region and its endpoints | Strict regional isolation requirements |
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.
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
Secret Manager Admin
Full control of secrets, versions and permissions. Keep to a very small group.
Secret Manager Secret Accessor
Can read the payload of secret versions. Give to workloads that must use the secret, and to nobody else.
Secret Manager Secret Version Adder
Can add new versions but not read existing values. Useful for rotation jobs.
Secret Manager Secret Version Manager
Can disable, enable and destroy versions without reading payloads.
Secret Manager Viewer
Can see metadata and list secrets but not read values.
Principles for granting access
Grant at the Secret Level
Give each workload access only to the specific secrets it needs, not to every secret in the project.
Use Dedicated Service Accounts
One service account per workload, so permissions and audit trails are clear.
Separate Reading from Managing
People who manage secrets should not automatically be able to read their values, and vice versa.
Add Conditions Where Useful
Use IAM conditions to limit access by time or by resource name patterns, for temporary needs.
Review Regularly
Check who can read which secrets and remove access that is no longer needed.
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.
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.
Encryption in Transit
Requests and responses travel over encrypted connections, protecting values on the network.
Encryption at Rest with Google-Managed Keys
The default. Secrets are encrypted before being stored, and Google manages the keys.
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
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.
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
A safe rotation pattern
Create the New Credential
Generate a new password or key in the target system while the old one still works.
Add a New Version
Store the new value as the newest version of the secret.
Let Workloads Pick It Up
Applications fetch the new value on restart or refresh, and keep working throughout.
Verify and Retire the Old Credential
Confirm no one uses the old value, then remove it from the target system.
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
Expiration Time or Lifetime
A secret can be set to expire and be deleted automatically, useful for temporary credentials.
Delayed Version Destruction
A waiting period before a destroyed version is permanently erased, allowing recovery from mistakes.
Rotation Notifications
Scheduled events published to Pub/Sub so automation can act at the right time.
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.
| Approach | How It Works | Strength | Weakness |
|---|---|---|---|
| Pin a specific version | The application always requests, for example, version 3 | Predictable and repeatable; no surprise changes | You must update the reference to adopt a new version |
| Use the latest alias | The application requests the newest enabled version | Picks up rotations automatically | A 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.
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.
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.
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.
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.
Cloud Functions
Functions can reference secrets as environment variables or mounted files in a similar way.
Google Kubernetes Engine
Secrets can be delivered to pods through integrations such as a secrets store driver, or fetched by applications using workload identity.
Compute Engine
Applications on virtual machines fetch secrets using client libraries or the API with the machine’s service account.
Cloud Build
Build steps can access secrets at build time without placing them in the build configuration or logs.
Other Systems
Any application, inside or outside Google Cloud, can use the API with proper credentials, including through federation.
Three delivery styles
| Style | How the App Gets the Secret | Considerations |
|---|---|---|
| Fetch through the API or client library | The code requests the secret when needed | Most flexible; supports refresh; requires code changes |
| Mounted file or volume | The platform places the secret as a file the app reads | No code change to the vault; can pick up new versions for the latest alias; avoids exposure through process environment |
| Environment variable | The platform injects the value into the process environment at start | Simple; 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]
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.
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
Admin Activity
Creating, changing or deleting secrets and permissions. Recorded by default.
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
| Event | Why It Matters |
|---|---|
| Access by an unexpected identity | May indicate stolen credentials or misconfiguration |
| Spike in access volume | Could mean a scraping attempt or a looping application |
| Permission changes on secrets | Someone may be widening access to read values |
| Destruction or disabling of versions | May cause outages, or be an attempt to hide evidence |
| Access from unusual locations or at unusual times | Potential sign of misuse |
| Failed access attempts | Possible probing for secrets |
Enable Data Access Logs
Turn on logging for Secret Manager at the appropriate level.
Route Logs Centrally
Send them to a protected, central location with controlled retention.
Create Alerts
Build log-based alerts for the high-risk events above.
Review and Tune
Check which identities legitimately read which secrets and refine alerts to reduce noise.
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.
Private Google Access
Workloads without public addresses can reach Secret Manager over Google’s network.
Private Service Connect
Use a private endpoint address in your own network to reach Google APIs, including Secret Manager.
VPC Service Controls
Define a perimeter that restricts Secret Manager access to approved projects and networks, reducing the risk of exfiltration with stolen credentials.
Organization Policies
Enforce rules such as allowed locations for secrets or customer-managed key requirements.
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.
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.
| Situation | Better Choice | Why |
|---|---|---|
| One Google Cloud service calling another | Attached service account | No secret to store or rotate |
| Outside pipeline calling Google Cloud | Workload identity federation | Short-lived tokens without keys |
| Connecting to a managed database | Identity-based database login where supported | Avoids a static password |
| Calling a third-party service with an API key | Secret Manager | The key must exist; vault protects it |
| Application needing a private signing key | Cloud KMS signing or Secret Manager | KMS can sign without exposing the key |
| Non-sensitive settings | Configuration service or environment settings | No 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]
14Secret Manager Compared with Other Options
Several places can hold sensitive values. Knowing the differences helps you choose.
| Option | What It Is | Best Fit | Limitations |
|---|---|---|---|
| Secret Manager | Managed vault for secrets with versions, IAM and audit | Passwords, tokens and keys used by applications | Small payloads; not a general configuration store |
| Cloud KMS | Managed cryptographic key service | Encryption, decryption and signing without exposing keys | Not meant for storing arbitrary secret values |
| Environment variables in code or configuration | Values set in plain settings | Non-sensitive configuration | Visible to anyone with access to the configuration; no audit or rotation |
| Source code or config files | Values written into repositories | Nothing sensitive | Leaks through history and copies |
| Cloud Storage objects | General object storage | Large files and non-sensitive data | No secret-specific versioning, rotation or access patterns |
| Self-hosted secret managers | Software you run yourself | Multicloud strategies or special features | You operate, secure and scale it |
| Configuration and parameter services | Stores for application settings | Non-secret settings with versions | Not designed for protecting sensitive values |
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.
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
Secrets Alongside Each Application
Each application’s project holds its own secrets. Simple permissions and clear ownership, but more places to manage.
Central Secrets Project
A dedicated, tightly controlled project holds secrets for many applications. Central governance, but requires careful per-secret permissions.
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.
Define the Secret Container as Code
Name, labels, replication, rotation settings and permissions are reviewed in version control.
Populate the Value Securely
A trusted process or person adds the first version outside of code.
Grant Per-Secret Access
The workload’s service account receives Secret Accessor on that secret only.
Monitor and Review
Audit logs and periodic reviews confirm that access matches intent.
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
Cache in Memory Only
Keep values in process memory, never written to disk or logs, and clear them when no longer needed.
Retry with Backoff
Handle brief errors by retrying with increasing delays rather than hammering the service.
Fail Safe at Startup
Decide whether a workload should refuse to start or run degraded if secrets cannot be fetched.
Mind Quotas
Large fleets starting at once can generate bursts of reads. Stagger rollouts and check current quotas.
Replicate for Availability
Use replication that matches your availability needs, especially for multi-region applications.
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.
Active Secret Versions
Billed per active version per month, and per replica location. Keeping many old enabled versions adds up.
Access Operations
Billed per set of access requests. Applications that fetch secrets on every request can create large volumes.
Rotation Notifications
Each rotation event published may have a charge.
Audit Logging Volume
Data access logs for busy workloads can create meaningful logging costs.
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
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.
Assume It Is Compromised
Treat any secret that was exposed as stolen, even if you see no evidence of misuse yet.
Create a New Credential
Generate a replacement in the target system and add it as a new secret version.
Switch Workloads to the New Value
Restart or refresh workloads so they use the new version.
Revoke the Old Credential
Invalidate the leaked value in the target system, and disable and later destroy the old version.
Investigate with Logs
Use audit logs and the target system’s logs to see whether the leaked value was used and by whom.
Fix the Root Cause
Find how it leaked, remove it from repositories, images and chats and add controls to prevent a repeat.
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.
Secret Scanning in Pipelines
Scan code and images for committed secrets before they are merged or published.
Pre-Commit Checks
Block commits containing secret-like strings on developer machines.
Short-Lived Credentials
Prefer credentials that expire quickly, limiting the usefulness of leaks.
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
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.
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.
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
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.
No. Versions cannot be edited. You add a new version with the new value and then disable or destroy older versions as appropriate.
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.
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.
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.
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.
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.
Usually not. Use attached service accounts and IAM, which provide short-lived credentials without storing any secret.
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.
Enable data access audit logs for Secret Manager. They record which identity accessed which secret and when, though they never record the secret value.
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.
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.