Complete Guide to Secrets Management
Manage application secrets securely in production: Vault, AWS, Azure, GCP, Kubernetes secrets, rotation, CI/CD, and when a manager is overkill.
Introduction
Hardcoded secrets in source code are the number one cause of data breaches. API keys, database passwords, encryption keys, and OAuth tokens must never live in code, config files committed to git, or CI logs, yet they end up there constantly, usually for convenience and occasionally by accident.
Secrets management is the discipline of storing, distributing, rotating, and auditing those values outside your codebase — and hardcoded credentials sit near the top of the OWASP Top 10 risk list for a reason. This guide compares the main tools (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager, Doppler), covers Kubernetes secrets and zero-downtime rotation, and — just as important — tells you when a full secrets manager is overkill for your setup.
Quick answers:
- Never commit secrets; env vars are better but still lack encryption, audit, and rotation.
- Single-cloud? Use the native manager (AWS/Azure/GCP). Multi-cloud or dynamic credentials? Vault. Small team? Doppler.
- On a leak, rotate first and investigate after — deleting the line doesn’t remove the secret from history.
- You don’t need a manager until you have several services, a compliance requirement, or coordinated rotation.
Why Not Environment Variables?
Environment variables are the default answer, and they’re better than hardcoded secrets — but they have real limits:
- No encryption at rest — env vars sit in plaintext in the process environment,
/proc, CI logs, and crash dumps. - No rotation — changing a value means redeploying or restarting every consumer.
- No audit trail — nothing records who read which secret and when.
- No fine-grained access — every process in the container sees every variable.
Env vars are fine for three services on one VPS. Past that — multiple teams, compliance requirements, dozens of consumers — you need a dedicated manager. The rest of this guide is about choosing and operating one.
Choosing a Secrets Manager
| Tool | Model | Best for | Watch out |
|---|---|---|---|
| HashiCorp Vault | Self-hosted or HCP SaaS | Multi-cloud, dynamic secrets, fine-grained policies | Operational overhead — you run the cluster |
| AWS Secrets Manager | Managed, per-region | AWS-native stacks, automatic RDS rotation | Per-secret pricing adds up at scale |
| Azure Key Vault | Managed | Azure-native, HSM-backed keys | Azure-centric; rotation less turnkey than AWS |
| GCP Secret Manager | Managed | GCP-native, IAM-integrated | Regional replication defaults; rotation is DIY |
| Doppler | SaaS, developer-first | Small teams, fast adoption | External dependency; fewer enterprise controls |
| Kubernetes Secrets | Built-in (etcd) | K8s workloads | Base64 ≠ encryption; needs KMS/external store |
The decision rule: if you’re all-in on one cloud, start with its native manager — zero operational overhead and IAM already wired. If you’re multi-cloud or need dynamic short-lived credentials, Vault pays for its complexity. If you’re a small team that just needs to stop committing .env, Doppler gets you there in an afternoon.
HashiCorp Vault
Vault is the most capable and the most demanding option — a self-hosted cluster that brokers every secret access behind policies, audit logs, and short-lived leases.
# Store a secret (KV v2 engine)
vault kv put secret/myapp/db username=app password=s3cret
vault kv get secret/myapp/db
# App authenticates and reads at runtime
vault read -format=json secret/data/myapp/db
Vault’s killer feature is dynamic secrets: instead of storing a static database password, Vault generates per-request credentials that expire automatically — a leaked credential self-destructs hours later instead of living until someone notices. Configuring a role that mints 1-hour Postgres credentials looks like this:
vault write database/roles/app \
db_name=my-postgresql \
creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';" \
default_ttl="1h" \
max_ttl="24h"
Each vault read database/creds/app returns unique credentials that die at the TTL. No rotation ceremony needed, because nothing static exists to rotate. The trade-off is operational cost: you run the cluster, manage unsealing, plan for HA, and write policies. Worth it at scale; heavy for a small team. For application code, the Python Vault recipe shows the client side.
AWS Secrets Manager
Fully managed, per-region, and deeply integrated with IAM — the path of least resistance on AWS.
aws secretsmanager create-secret --name myapp/db \
--secret-string '{"username":"app","password":"s3cret"}'
aws secretsmanager get-secret-value --secret-id myapp/db \
--query SecretString --output text
Its standout feature is automatic rotation for RDS/Redshift: attach a Lambda rotator and the database password changes on a schedule with no code changes:
aws secretsmanager rotate-secret \
--secret-id myapp/db \
--rotation-lambda-arn arn:aws:lambda:us-east-1:123456789:function:rotator \
--automatically-after-days 30
Access is plain IAM, so scope it tightly — a policy granting secretsmanager:GetSecretValue on arn:aws:secretsmanager:*:*:secret:myapp/*, ideally conditioned on aws:SourceVpc, keeps blast radius small.
The catch is pricing: per-secret monthly fees plus per-10k-call API charges, which gets expensive if every pod pulls a fresh secret every few seconds. Cache secrets client-side or use the Secrets Manager agent sidecar to keep calls sane.
Azure Key Vault
Managed, HSM-backed storage for secrets, keys, and certificates — the natural choice on Azure.
az keyvault secret set --vault-name my-vault --name db-password --value s3cret
az keyvault secret show --vault-name my-vault --name db-password --query value -o tsv
Key Vault shines when paired with Managed Identity — your app authenticates with its Azure identity and no credentials are needed to fetch credentials, eliminating the bootstrap-secret problem. Rotation exists but is less turnkey than AWS; you typically wire Event Grid events to a rotation Function yourself.
GCP Secret Manager
Google’s managed store, integrated with IAM and Cloud Audit Logs.
gcloud secrets create db-password --replication-policy=automatic
printf 's3cret' | gcloud secrets versions add db-password --data-file=-
gcloud secrets versions access latest --secret=db-password
# Grant a service account read access to one secret only
gcloud secrets add-iam-policy-binding db-password \
--member="serviceAccount:my-app@my-project.iam.gserviceaccount.com" \
--role="roles/secretmanager.secretAccessor"
Use secretAccessor for runtime access and keep secretAdmin for the humans and pipelines that manage secrets — never grant it to workloads.
Versioned secrets, regional or automatic replication, and access via service accounts. Rotation is do-it-yourself: schedule a Cloud Run job that calls versions add — but Secret Manager’s integration with GKE workload identity means pods fetch secrets with no stored credential, same bootstrap trick as Azure.
Doppler (SaaS Secrets Management)
Doppler is the developer-experience-first option — a SaaS that syncs secrets to environments, CI, and Kubernetes with a CLI that feels like git.
doppler secrets set DB_PASSWORD=s3cret
doppler run -- node app.js # injects secrets as env vars at runtime
No cluster to run, no IAM to wire: the fastest on-ramp for small teams. The trade-offs are the obvious SaaS ones: an external dependency in your critical path, and fewer enterprise controls than Vault. For a startup that needs to stop committing .env today, it’s often the right call.
Kubernetes Secrets
Kubernetes has a built-in Secret resource, and a persistent misunderstanding about it: base64 is encoding, not encryption. Anyone who can read the secret (or the etcd backup) can decode it.
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
data:
username: YXBw # base64("app")
password: czNjcmV0 # base64("s3cret") — NOT encrypted
To make K8s secrets actually secret:
- Enable encryption at rest via a KMS provider (
EncryptionConfiguration+ KMS plugin on the API server). - Restrict RBAC —
get/liston secrets should be tightly scoped;listleaks all values in a namespace. - Prefer external stores — External Secrets Operator or the Secrets Store CSI driver syncs from Vault/AWS/Azure, so the source of truth and rotation live outside the cluster.
If you’re on managed K8s, also verify etcd backups are encrypted — the secret data lives there, not just in the API.
Zero-Downtime Secret Rotation
Rotation is where theory meets pain: change a password and every running instance using the old one breaks. The safe pattern is overlap, not swap.
The steps that make rotation boring instead of terrifying:
- Create the new secret first — both old and new work simultaneously.
- Roll the deploy — instances restart/refresh and pick up the new value; canary first if you’re cautious.
- Verify all consumers migrated — check auth logs for the old credential going quiet.
- Revoke the old credential — last step, never first.
The classic mistake is revoking before the rollout finishes — that’s the self-inflicted outage every team does exactly once. Automate the sequence end-to-end (AWS does it for RDS; elsewhere it’s a scheduled job) and alert when a secret has not rotated within its policy window.
Secrets in CI/CD Pipelines
CI systems are a favorite leak vector: secrets print to logs, get baked into artifacts, or land in shell history. The rules:
- Mask and scope: mark every secret as masked in the CI settings; scope it to the pipelines that need it, not the whole org.
- OIDC over static keys: GitHub Actions, GitLab CI, and friends can mint short-lived cloud credentials via OIDC — no stored AWS keys to leak at all.
- Never echo secrets: no
echo $SECRETfor “debugging” — masks help but process args still leak. - Scan the pipeline itself: a CI config file is code; scan it for secrets like anything else. The CI/CD security guide covers the rest of the pipeline-hardening checklist.
The OIDC setup in GitHub Actions is a few lines — the job mints a short-lived token, no AWS keys stored anywhere:
jobs:
deploy:
permissions:
id-token: write
contents: read
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789:role/GitHubActionsRole
aws-region: us-east-1
Secret Scanning in Git
Rotation fixes leaked secrets; scanning catches them before they need fixing. Tools like gitleaks or trufflehog run in pre-commit hooks and CI to block credentials from ever reaching the repository.
# Scan the whole history, not just HEAD — secrets hide in old commits
gitleaks detect --source . --verbose
When a scan hits, remember: rotating beats deleting. Removing the line doesn’t remove the secret — it lives in git history, forks, and anyone’s clone. Rotate the credential first, then decide whether history surgery (BFG/git-filter-repo) is worth it. For a credential that was valid for even a few minutes, assume compromise.
Access Policies and Auditing
Whoever can read a secret can leak it. Two controls keep that surface small:
- Least privilege by default — apps get read access to the exact paths they need (
secret/data/myapp/*), notsecret/*; humans get access through groups, not ad-hoc policies. - Audit everything — every read/write should produce a log entry with identity and timestamp. Vault writes audit devices to syslog/files; cloud managers integrate with their platform’s audit trail (CloudTrail, Azure Monitor, Cloud Audit Logs). Review these — a secret read at 3am from an unknown IP is the detection, not just the hygiene.
The same least-privilege model applies inside your app, not only at the secrets store — Implement RBAC covers role hierarchies and middleware enforcement end to end.
How Apps Consume Secrets
Picking a manager is half the problem; how the secret reaches your process is the other half. Four patterns cover almost everything:
- Env vars injected at deploy — the platform (K8s envFrom, ECS task defs, GitHub Actions
env:) pulls from the store and exposes values as env vars. Simple, universal, and the secret never lands in code — but it does live in the process environment, readable by anything that can exec into the container. - Mounted files — a secret written to a tmpfs volume (
/run/secrets/db-password). Better than env: files don’t show up in/proc/*/environor crash dumps, and rotation can update the file without a restart if the app re-reads it. - SDK calls at runtime — the app calls the manager’s API on startup (or per-request with caching). Strongest pattern for dynamic secrets (Vault leases, short-lived AWS creds) because the app fetches exactly when it needs to and the manager can revoke mid-flight.
- Sidecar/agent injection — an init container or sidecar (Vault Agent Injector, AWS Secrets & Configuration Provider) fetches secrets and shares them via a mounted volume. Ops-controlled and app-transparent: the app reads a file and never knows a manager exists.
The rule of thumb: env vars for non-sensitive config and simple cases, mounted files or sidecars for production credentials, SDK calls when you need dynamic secrets or fine-grained audit per access.
Cost and Operational Trade-offs
Each option has a bill attached, and it’s not always money:
- Vault — free as software, expensive as operations. You pay in the cluster you run, the unsealing ceremony, upgrades, and someone who actually understands Raft HA. At small scale it’s the most expensive option measured in engineer-hours.
- AWS/Azure/GCP managers — charge per secret per month plus API calls (AWS ~$0.40/secret + $0.05 per 10k calls). Cheap until you have thousands of secrets or chatty pods pulling constantly — then client-side caching becomes a cost control, not just a performance optimization.
- Doppler and SaaS — per-seat or per-secret pricing; predictable for small teams, grows with headcount.
- Kubernetes Secrets — free and already there, but you pay in the gap between “stored” and “secured”: encryption-at-rest setup, RBAC discipline, and usually an external source of truth anyway.
The honest math: a small team on one cloud usually can’t beat the native manager’s total cost — the engineering time to run Vault well exceeds the AWS bill for a long time.
A Practical Rollout Plan
Adopting secrets management doesn’t need a big-bang migration:
- Week 1 — inventory.
gitleaks detectyour repos, grep forpassword|secret|api_key, and list every credential you can find. Most teams are surprised at the count. - Week 2 — pick the store. Cloud-native if you’re single-cloud; move the highest-sensitivity secrets first (production database, payment keys).
- Week 3 — wire consumption. One service end-to-end: identity-based access, env or sidecar injection, app reads from the store path. Prove the pattern before scaling it.
- Month 2 — rotate. Schedule the first rotation for the migrated secrets; the overlap rollout above makes this a non-event.
- Ongoing — scan and audit. gitleaks in pre-commit and CI, quarterly review of who can read what.
Most teams stall trying to migrate everything at once. The pattern that works is inventory → migrate the crown jewels → prove one service → then scale.
When You Don’t Need a Secrets Manager
Not every project needs Vault on day one:
- A single small service — env vars via your host’s secret mechanism (GitHub secrets, systemd
EnvironmentFilewith0600, container orchestrator env injection) is fine. The risk is scale and sprawl, not the pattern itself. - Local development —
.envfiles in.gitignoreare the norm; just make sure the file never commits and developers know never to paste real production values into it. - Prototypes — a throwaway script doesn’t need dynamic secrets; it needs you to not commit the key.
The honest guideline: reach for a manager when you have more than a handful of services, a compliance requirement, or the first rotation that needs coordination across consumers. Before that, disciplined env vars cover you — the mistake is not using env vars early, it’s never graduating past them.
Incident Response: When a Secret Leaks
A leaked credential is a race, not a ticket. The steps in order:
- Rotate immediately. Don’t wait to understand the scope — a credential that was exposed for five minutes is compromised. Rotate first, investigate after.
- Check audit logs. Who read or used the credential between exposure and rotation? Vault audit devices and cloud audit trails answer this — which is why step six in best practices (audit everything) exists.
- Identify all consumers. A leaked DB password usually has more than one service using it — rotate everywhere, not just the app that leaked it.
- Find the leak vector and close it. Git history, CI log, support ticket, Slack message: the rotation is worthless if the same path leaks the new value tomorrow.
- Assume downstream compromise. If the credential guarded data, assess what was reachable — a leaked API key may mean exfiltrated data, not just a bad key.
The mistake teams make here is treating leak response as optional because “it was only in a private channel”. Private channels leak; the only question is whether the credential still works when it does.
Best Practices
- Never commit secrets — not in code, config, tests, or “temporary” files. Assume anything in git is public.
- Encrypt at rest and in transit — TLS to the manager, KMS/encryption backend behind it.
- Rotate on a schedule and on suspicion — the window where a leaked credential works is the whole point.
- Short-lived credentials over long-lived ones — dynamic secrets and OIDC beat static keys everywhere they exist.
- Audit access — logging who read what turns a breach into a traceable event.
- Separate by environment — dev/staging/prod secrets never share a store path or a value.
- Bootstrap carefully — the chicken-and-egg problem is real: prefer managed identity, IRSA, or workload identity over injecting a “master” secret to fetch the rest.
Common Mistakes
.envcommitted to git — the classic, still the most common leak. Scan history, rotate, and add to.gitignorepermanently.- Secrets in CI logs — masking helps, but
curl --header "Authorization: Bearer $TOKEN"still prints the command line. Never interpolate secrets into command strings. - Treating base64 as encryption — K8s secrets are encoded, not encrypted, until you add a KMS provider.
- No rotation plan — a secret that never changes is a secret waiting to leak forever. If rotation requires downtime, that is a design problem to fix, not a reason to skip it.
- One secret for everything — a single DB password shared by ten services means one leak compromises all ten. Per-service credentials, always.
- Secrets in container images —
ENV SECRET=...in a Dockerfile bakes it into every layer forever. Inject at runtime, never at build.
See Also
- HashiCorp Vault documentation — official docs for Vault’s engines, auth methods, and dynamic secrets.
- AWS Secrets Manager docs — managed secrets and automatic RDS rotation.
- OWASP Secrets Management Cheat Sheet — operational best practices.
- External Secrets Operator — syncing external stores into Kubernetes.
- Guides: complete-guide-owasp-top-10-2025 — where hardcoded secrets sit on the risk list.
- Guides: ci-cd-security-guide — securing pipelines that handle secrets.
- Guides: complete-guide-supply-chain-security — where keyless OIDC signing removes stored keys entirely.
- Guides: complete-guide-authentication-patterns — the credentials these secrets protect.
- Docs: serverless-security-checklist — runtime loading, rotation and caching of secrets in functions.
- Recipes: python-secrets-management-vault — fetching Vault secrets in Python.
- Companion scripts — secret rotation, repo scanning, and an ExternalSecret manifest you can run.
Frequently Asked Questions
What is the difference between a secrets manager and environment variables?
Environment variables are a delivery mechanism, a way to get a value to a process. A secrets manager adds what env vars lack: encryption at rest, fine-grained access control, an audit trail of every read, and rotation without redeploys. You typically use both: the manager stores and rotates, env vars (or SDK calls) deliver to the app.
How often should I rotate secrets?
Rotate on a schedule based on sensitivity (30–90 days for database credentials is common — and immediately on any suspected exposure. With automated rotation (AWS native, Vault dynamic secrets) the marginal cost of frequent rotation is near zero, so err toward more often.
Is Kubernetes Secrets encrypted?
Not by default; K8s stores them base64-encoded, which is encoding, not encryption. Enable encryption at rest with a KMS provider on the API server, restrict RBAC on get/list, or use an external store via External Secrets Operator or the Secrets Store CSI driver.
Should I use Vault or a cloud-native secrets manager?
Cloud-native (AWS/Azure/GCP) if you are single-cloud — managed, IAM-integrated, zero ops. Vault if you're multi-cloud, need dynamic short-lived secrets, or need fine-grained policies the native tools lack. Vault costs operational overhead; the cloud managers cost per-secret and per-call fees.
What do I do if a secret is committed to git?
Rotate the credential first — deleting the line doesn't remove the secret from history, forks, or clones. Then decide whether history rewriting (BFG, git-filter-repo) is worth it for your repo, and add secret scanning (gitleaks, trufflehog) to pre-commit and CI so it doesn't happen again.
Can a secrets manager work for a small team?
Yes. Managed options (AWS Secrets Manager, Doppler) have almost no operational cost. A small team doesn't need Vault's complexity, but it does need to stop committing .env and to rotate occasionally. The manager choice scales with your infrastructure, not your headcount.
How do I handle the bootstrap secret problem?
Avoid injecting a master credential to fetch the rest; use workload identity instead: AWS IRSA, GCP/GKE workload identity, Azure Managed Identity, or Vault's Kubernetes auth method. The platform vouches for the workload's identity, and no static credential needs to exist anywhere.
Related Resources
Complete Guide to OWASP Top 10 2025
Mitigate each risk in the OWASP Top 10 2025 list with practical code examples. Covers the new supply chain and exception-handling categories, plus the reordered classics.
GuideComplete Guide to API Security
Secure your APIs end-to-end: rate limiting, auth, input validation, CORS, injection prevention, gateway patterns, audit logging, and testing.
GuideCI/CD Pipeline Security: Prevent Supply Chain Attacks
A practical guide to securing CI/CD pipelines: secrets management, least-privilege runners, artifact signing, and supply chain defense.
RecipeManage Application Secrets with HashiCorp Vault and Python
Store, retrieve, and rotate application secrets securely using HashiCorp Vault with Python hvac client, dynamic secrets, and automatic lease renewal.
GuideComplete Guide to Authentication Patterns
Implement production authentication: JWT, OAuth2, sessions, passkeys, MFA, SAML and OIDC SSO, RBAC vs ABAC, and secure token rotation with code.