Secrets Management: Vault, Kubernetes Secrets, and Env Vars
Learn how to securely manage secrets, API keys, and credentials across microservices using HashiCorp Vault, Kubernetes Secrets, and best practices.
Secrets management controls which identities can use credentials, where values are stored, and how they are rotated. This guide compares Kubernetes Secrets with Vault and external stores, then walks through workload identity, CI/CD, monitoring, and incident response. It helps teams choose a setup they can operate, protect audit trails, and refresh credentials without disrupting services.
Secrets Management: Vault, Kubernetes Secrets, and Environment Variables
Introduction
A service keeps starting successfully until its shared database password leaks or a rotation reaches some workloads but not others. That is the operational problem secrets management addresses: controlling who receives credentials, how long they remain valid, and how teams replace them safely.
This guide compares Kubernetes Secrets with dedicated stores such as Vault, then covers workload identity, rotation, CI/CD, monitoring, and incident response. The right choice depends on the sensitivity of the data and your team’s ability to operate it; a secret store helps only when access and refresh paths are managed too.
Core Concepts
Not all secrets are the same. The distinction between static and dynamic secrets affects both security and operational complexity.
Static Secrets
Static secrets are long-lived credentials that do not change unless someone manually rotates them. Database passwords, API keys, static TLS certificates fit here. These secrets persist for weeks, months, or even years.
The rotation problem is real. If a database password never changes and someone obtains it through a breach, they have permanent access until you manually update it. Most organizations update static secrets infrequently because rotation requires coordinating changes across multiple services and environments, a painful process that often introduces downtime risk.
Static secrets are fine when the secret is external — an API key for a third-party service you do not control, for instance. You cannot ask Stripe to issue a new API key every hour. For internal credentials, static secrets create a permanent attack surface. If one service in your system gets compromised and it uses a shared static database password, the attacker has the keys to your entire database.
The other problem with static secrets is auditing. When the same credential is used by 50 services and something goes wrong, you cannot tell which service was compromised. Dynamic secrets solve this by giving each service its own credential tied to its identity.
Dynamic Secrets
Dynamic secrets are generated on-demand with short lifespans — minutes to hours. A service requests temporary credentials and they expire before an attacker can do much with them. Vault, AWS Secrets Manager, and GCP Secret Manager support this.
The immediate benefit is blast radius containment. If one service is compromised, the attacker gets credentials valid for maybe an hour. After that, Vault revokes the lease and the credentials stop working. The attacker would need to be in your system continuously to maintain access.
The operational benefit is auditing. Every dynamic credential is unique to one service. When you see a bad login in your database, you know exactly which service account was used and can trace it back to a specific pod or workload. No guessing which of your 50 services leaked a shared password.
Kubernetes Secrets
Kubernetes has a built-in Secrets resource, but it has limitations that catch many teams off guard.
How Kubernetes Secrets Work
Kubernetes Secrets use base64 encoding. Creating a secret looks like this:
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
data:
username: cG9zdGdyZXM=
password: c2VjcmV0cGFzc3dvcmQ=
The values are base64 encoded, not encrypted. An identity with permission to read a Secret, or enough access to inspect a workload that consumes it, may be able to retrieve its value. Run echo “cG9zdGdyZXM=” | base64 -d and you get the plaintext username.
Kubernetes does not encrypt Secret data in etcd by default. Enable encryption at rest and verify the cluster provider’s settings; managed services may configure it for you, while self-hosted clusters need explicit setup.
The Real Limitation
Kubernetes Secrets are API objects whose values are base64-encoded; the encoding provides no protection. RBAC can restrict access to Secret objects, but it does not provide per-key policies, lease-based expiration, or the rotation and audit workflows of a dedicated secrets manager. Namespace separation alone is not a complete access-control strategy.
Teams use Kubernetes Secrets because they are built-in and simple, then hit problems when they need audit logs, automatic rotation, or integration with external secret stores.
For small deployments or early-stage projects, Kubernetes Secrets might be enough. For production systems handling sensitive data, you will probably need something more robust.
HashiCorp Vault
Vault is a dedicated secrets management tool that addresses the gaps in Kubernetes Secrets. It gives you centralized secret storage, dynamic secrets, encryption as a service, and detailed audit logs.
Vault Architecture
Vault uses an architecture that separates concerns cleanly:
graph TD
subgraph Clients
S1[Service A]
S2[Service B]
S3[Service C]
end
subgraph Vault
SA[Storage Backend]
LS[Logical System]
PL[Plugin Layer]
end
S1 -->|Request secrets| LS
S2 -->|Request secrets| LS
S3 -->|Request secrets| LS
LS -->|Persist| SA
LS -->|Execute| PL
SA[(Storage<br/>etcd/Consul/S3)]
The storage backend holds encrypted data. The logical system handles the API and secret engines. The plugin layer extends functionality for things like PKI certificates or cloud provider integrations.
Secret Engines
Vault organizes secrets into logical paths called secret engines. Each engine handles a specific type of secret and exposes a REST API for programmatic access. Knowing which engine to reach for is the first thing to get right with Vault.
The Key-Value (KV) v2 engine is the workhorse for most teams. It stores static secrets at paths you define, like secret/myapp/database or secret/myapp/api-keys. KV v2 adds versioning and metadata on top of v1, which matters when you need to audit changes or recover from accidental deletes. The path structure looks like secret/data/myapp/db-creds where data is the KV v2 prefix. Use KV for anything that does not need dynamic generation: third-party API keys, database passwords you rotate manually, SSH keys, or any credential with a fixed value.
The Database engine is where Vault’s dynamic secret generation makes the most sense. Instead of sharing one database password across all your microservices, Vault creates per-service credentials that expire automatically. Configure the database engine once with your PostgreSQL or MySQL connection details, then define roles like myapp-readonly or myapp-service that specify what permissions the generated credentials get. When your service starts, it asks Vault for credentials and gets a unique username and password valid for one hour. When the lease expires, Vault revokes the credential automatically. A compromised service account has a narrow window of usefulness — after an hour, the credential is dead.
The PKI engine handles TLS certificates end to end. Point it at your certificate authority configuration, define certificate roles with specific CN/SAN constraints, and Vault issues certificates on demand. The issued certificates have short TTLs by default — 1 hour to a few days. This sounds like a hassle but it is actually a security feature: a compromised certificate is only useful briefly. Vault also handles renewal automatically, so your services can hold certificates without manual re-issuance. For internal services using mTLS or for services that need publicly-trusted certificates via Let’s Encrypt, the PKI engine can replace cert-manager in simpler setups.
The AWS engine works the same way as the Database engine but for AWS IAM credentials. Instead of embedding long-lived AWS access keys in your application, Vault issues temporary STS tokens scoped to specific IAM roles. The credentials expire after a configurable TTL, typically 1 hour. GCP, Azure, and other cloud providers have equivalent engines following the same pattern. Vault gives you a single control plane for credentials across all of them, which is useful if you run multi-cloud.
The Kubernetes engine bridges Vault and Kubernetes more tightly than the Kubernetes auth method alone. It can mint Kubernetes service account tokens, manage their lifecycle, and sync secrets into Kubernetes Secrets. For teams running Vault outside Kubernetes but needing deep Kubernetes integration, this engine provides the glue. Most teams find the Kubernetes auth method alone is sufficient. The option exists for more advanced use cases like ClusterRole propagation or cross-namespace secret distribution.
Authentication Methods
Services do not just retrieve secrets - they authenticate to Vault first. Vault supports multiple authentication methods:
- Kubernetes Service Account: Uses Kubernetes service account tokens to authenticate. The most common approach for services running in Kubernetes.
- AppRole: A role-based authentication method for machines or applications.
- JWT/OIDC: For services using JWT-based authentication.
- TLS Certificates: For services with valid client certificates.
The typical flow for a Kubernetes workload looks like this:
- Pod starts and gets its service account token mounted
- Pod authenticates to Vault using its Kubernetes service account
- Vault validates the token with Kubernetes
- Vault returns the requested secrets
- Pod uses secrets to connect to databases or other services
Dynamic Secrets in Action
The database secret engine demonstrates Vault’s power. Instead of sharing a static database password across all services, each service gets its own temporary credentials:
# A service requests database credentials
vault read database/creds/myapp-role
# Vault returns temporary credentials
Key Value
--- -----
lease_id database/creds/myapp-role/xyz123
lease_duration 1h
username v-token-myapp-role-xyz123
password A1a-xxxxxxxxxxxxx
The service uses these credentials to connect to the database. After one hour, Vault revokes the credentials automatically. The next time the service needs database access, it requests new credentials from Vault.
This approach means no service ever knows the master database password. Compromise of one service only exposes temporary credentials that expire quickly.
Service Accounts and Workload Identity
Modern microservices should not rely on shared static credentials. Workload identity provides cryptographically verifiable identity for services running in cloud environments or Kubernetes.
SPIFFE (Secure Production Identity Framework for Everyone) defines a standard for workload identity. SPIFFE IDs are URIs that uniquely identify workloads:
spiffe://example.com/ns/payment/sa/payment-service
This SPIFFE ID can be embedded in X.509 certificates or JWTs, letting services prove their identity without shared secrets. Service mesh solutions like Istio and Linkerd automatically issue SPIFFE certificates to workloads.
Workload identity shifts the security model from “protect the secrets” to “verify the identity”. Instead of obsessing about database passwords being leaked, you verify that the service presenting credentials is actually the payment service.
Vault supports SPIFFE-based authentication through its Kubernetes auth method. Services can authenticate using their SPIFFE IDs and receive Vault secrets based on their identity.
Secret Rotation Strategies
Rotation is where many secret management strategies fall apart. A good rotation strategy should be automated, have minimal blast radius, and not require downtime.
Rotation Patterns
Time-based rotation: Secrets expire after a fixed period. Services get new credentials before expiration. Simple approach but requires services to handle credential refresh gracefully.
Event-based rotation: Rotation triggers on specific events - a suspected compromise, an employee leaving, a compliance requirement. This requires coordination across services but ensures secrets do not persist indefinitely after a security incident.
Usage-based rotation: For dynamic secrets from Vault, rotation happens automatically on a schedule. Services always have fresh credentials without manual intervention.
Time-based rotation works for static secrets but requires coordination. You update the secret in your secrets manager, then update all services that use it. If you miss a service, it loses access when the old secret expires. The coordination overhead makes this error-prone at scale.
Event-based rotation is what you do when something bad happens. A breach, a terminated employee, a compliance audit. The challenge is that rotation has to be fast and comprehensive. If you rotate a database password because an employee left, every service that uses that password needs the new one immediately. This is where dynamic secrets shine — the secrets manager handles distribution automatically.
Usage-based rotation is how Vault handles dynamic secrets. The lease has a fixed TTL, and Vault renews it as long as the service is running and the secret is still needed. When the service terminates, the lease expires and the credentials are revoked. This matches how workloads actually behave — services start, run, and stop, and their credentials should follow the same lifecycle.
Implementing Rotation
The key to successful rotation is designing services to handle credential refresh:
- Cache credentials locally
- Before using a credential, check if it is about to expire
- If expiring soon, request new credentials proactively
- Handle authentication failures gracefully and retry with fresh credentials
Many teams use a sidecar container that handles credential refresh. The sidecar communicates with Vault, stores credentials in a shared volume, and the main container reads from that volume. This separation lets you update the sidecar logic without touching your application.
External Secrets Operators
External Secrets Operators (ESO) integrate external secret stores like Vault, AWS Secrets Manager, or GCP Secret Manager with Kubernetes. Instead of manually copying secrets into Kubernetes, you reference external secrets in your Kubernetes manifests.
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: db-credentials
spec:
refreshInterval: 1h
secretStoreRef:
name: vault-backend
kind: SecretStore
target:
name: db-credentials
creationPolicy: Owner
data:
- secretKey: password
remoteRef:
key: secret/myapp/db-password
property: password
When you apply this manifest, the operator syncs the secret from Vault into a Kubernetes Secret. The operator handles rotation based on the refresh interval.
This gives you the best of both worlds: secrets live in your centralized secrets store with full audit logs and access control, while your applications keep using standard Kubernetes Secrets.
The External Secrets Operator supports multiple backends: Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager, and more.
CI/CD and GitOps Integration
Secrets management does not stop at runtime. CI/CD pipelines need access to secrets to deploy applications. GitOps workflows need secrets to synchronize configuration.
Injecting Secrets at Deploy Time
The pattern that works well: secrets never live in git, but CI/CD pipelines retrieve them at deploy time. Your deployment process looks like this:
- CI/CD pipeline triggers on a git commit
- Pipeline authenticates to Vault or your cloud secrets manager
- Pipeline retrieves the required secrets
- Secrets are injected into the pod at deploy time (via dynamic secrets or ESO)
- Application runs with short-lived credentials
Many teams use Kubernetes service account JWTs for this. The CI/CD runner has a service account with permissions to request specific secrets from Vault.
GitOps Considerations
In a GitOps model, your desired state lives in git. The problem is reconciling the fact that secrets cannot live in git.
The solutions:
- External Secrets Operator: Reference external secrets in your git manifests. The operator syncs actual values from your secrets store.
- Sealed Secrets: Encrypt secrets before committing to git. Only the cluster can decrypt them.
- Vault Agent: Run a vault agent sidecar that handles authentication and secret retrieval.
The External Secrets Operator approach has become popular because it keeps git manifests clean and relies on established external secrets stores for the actual sensitive values.
When to Use / When Not to Use
| Scenario | Use This Approach | Notes |
|---|---|---|
| Production microservices with dynamic scaling | Vault Dynamic Secrets | Short-lived credentials work well with scaling |
| Small project or early-stage startup | Kubernetes Secrets | Simpler to start, but plan migration to Vault |
| CI/CD pipeline credentials | Vault or Cloud Secrets Manager | Centralized audit trail for pipeline access |
| Multi-cloud or hybrid environment | Vault | Cloud-agnostic, works across AWS/GCP/Azure |
| Database credentials for PostgreSQL/MySQL | Vault Database Secrets Engine | Dynamic credentials per service |
| TLS certificates | Vault PKI or cert-manager | cert-manager is simpler for Kubernetes-native; Vault for unified secrets |
| External third-party API keys | Vault KV with rotation | Static but with automated rotation |
| Kubernetes-native only, simple needs | Kubernetes Secrets + ESO | External Secrets Operator syncs from external stores |
| Legacy VMs outside Kubernetes | Vault Agent Sidecar | Vault works outside K8s too |
Trade-Off Table
| Aspect | Kubernetes Secrets | HashiCorp Vault |
|---|---|---|
| Encryption at rest | Requires explicit config (etcd encryption) | Encrypted by default |
| Dynamic secrets | No native support | Database, AWS, GCP, PKI engines |
| Secret rotation | Manual or via external tools | Native rotation engines |
| Access control | RBAC only (namespace, SA) | Fine-grained policies per path |
| Audit logging | Basic K8s events | Comprehensive audit log |
| High availability | Built into K8s control plane | Requires HA configuration |
| Learning curve | Low | Higher |
| Cost | Included with K8s | Open source free; Enterprise for advanced features |
When Not to Use Plain Kubernetes Secrets
Plain Kubernetes Secrets work for development clusters and early-stage projects where the blast radius of a compromise is acceptable. They fall short in several scenarios that catch up with most teams eventually.
When secrets contain sensitive data, base64 encoding is not encryption. Anyone with cluster access — a developer with kubectl permissions, a CI/CD pipeline service account, anyone who can read pods — can decode the secret with a single command. Run kubectl get secret myapp-creds -o jsonpath=‘{.data.password}’ | base64 -d and the password is in plaintext. In a compliance environment, auditors will flag this immediately. The data is stored in plaintext in etcd unless you have explicitly enabled encryption at rest, and even then, anyone with API access reads the plaintext.
In production systems with compliance requirements, Kubernetes does not give you an audit log of which service account accessed which secret. SOC 2, PCI-DSS, and HIPAA all require knowing who accessed what and when. Kubernetes events capture some audit trail, but they do not record the actual secret values or the full context of which workload accessed which path. Vault’s audit log is comprehensive by design — every read, write, and authentication attempt is logged with the client identity, source IP, and timestamp. If you are under audit, Kubernetes Secrets alone will not give your auditor what they need.
Multi-team clusters where separation is needed expose another limitation. Kubernetes RBAC can restrict who can read Secrets within a namespace, but within a namespace, access control is coarse-grained. If the payment team and the logging team share a namespace, both teams’ service accounts can read both teams’ secrets. Namespace isolation helps between teams, but within a team, there is no way to say “service account A can only read secrets from path X.” Vault’s policy language supports path-level access control that Kubernetes RBAC cannot match.
When you need dynamic credentials, Kubernetes Secrets are static by design. You create a secret, it persists until you update it, and nothing expires automatically. Credential rotation becomes a manual process that requires coordinating changes across services and environments. Vault’s Database and AWS engines automatically expire and renew credentials. A credential that lives for one hour eliminates the class of attacks that rely on long-lived static credentials persisting indefinitely.
Best Practices
Managing secrets well requires consistent discipline across your organization. These practices matter most.
Never Commit Secrets to Version Control
This should go without saying, but it keeps happening. API keys, database passwords, and private keys should never appear in git repositories. Not even in private repositories.
Use tools like git-secrets, Talisman, or pre-commit hooks to scan commits for accidentally committed secrets. Treat any secret that appears in version control as compromised. Rotate it immediately.
A .gitignore file should exclude any file that might contain secrets. Be particularly careful with .env files, config maps, and any file with “secret” or “credential” in the name.
Least Privilege Access
Services should only have access to the secrets they need. A logging service does not need database credentials. An API service does not need access to your payment processing secrets.
In Vault, define policies that restrict which paths each service can read. In Kubernetes, use RBAC to limit who can read Secrets in each namespace.
Audit access regularly. Who is actually reading secrets in production? Are there services that request secrets they no longer use? Periodic reviews catch accumulation of unnecessary access.
Audit Everything
You need to know who accessed what, when, and from where. Vault provides comprehensive audit logging including:
- Every authentication attempt (success and failure)
- Every secret read
- Every secret created or updated
- Client identity and source IP for each request
Cloud providers offer similar logging for their secrets managers. Enable those logs and ship them to your SIEM or log aggregation system.
Audit logs serve multiple purposes: detecting unauthorized access, troubleshooting operational issues, and meeting compliance requirements.
Use Short-Lived Credentials
Dynamic secrets with short lifespans reduce risk significantly. If a credential expires in 15 minutes, an attacker has a narrow window to use it. Static credentials that last a year give attackers plenty of time.
Where dynamic secrets are not possible, use the shortest acceptable lifetime for static secrets. Review password policies and certificate expiration periods. Do you really need that API key to last forever?
The math is simple. A credential with a 1-year TTL gives an attacker 365 days to find and exploit it. A credential with a 24-hour TTL gives them at most 24 hours. Even if an attacker exfiltrates a database password, it might expire before they can use it.
Short-lived credentials also force rotation, which catches another class of bugs. If your credential rotation process works, you will notice when it breaks because services start failing. That failure is a signal, not just a problem. With long-lived credentials, rotation can silently break and nobody notices until you do an audit.
The practical ceiling for static credentials is around 90 days for most use cases. Anything longer should have a specific justification. Certificates can often be shorter — 30 days is reasonable for TLS certificates if you have automated renewal.
Production Failure Scenarios
Failure Scenarios and Mitigations
Scenario: Vault Unavailable
Symptoms: Services cannot retrieve secrets. Applications fail to start or start with stale cached credentials. Dynamic credentials stop working.
Diagnosis:
# Check Vault pods
kubectl get pods -n vault -l app=vault
# Check Vault status
kubectl exec -n vault vault-0 -- vault status
# Check for seal status
kubectl exec -n vault vault-0 -- vault status | grep Sealed
# Test Vault API
kubectl exec -n vault vault-0 -- curl -s http://localhost:8200/v1/sys/health
Mitigation:
- If Vault is sealed, unseal it using stored unseal keys (auto-unseal is preferred for production)
- If Vault pods are down, check resource constraints (OOMKilled) or scheduling issues
- Services with cached secrets may continue working if cache is still valid
- If Vault is overloaded, check request volume, storage latency, and resource limits; use only the HA or performance-scaling options supported by your Vault edition.
Prevention:
- Use auto-unseal with cloud KMS (AWS KMS, GCP Cloud KMS, Azure Key Vault)
- Run Vault in HA mode with multiple pods
- Configure pod anti-affinity for Vault servers
- Monitor Vault health and set alerts for sealed/unavailable status
Scenario: Kubernetes Service Account Token Not Validating Against Vault
Symptoms: Services cannot authenticate to Vault using Kubernetes auth method. Logs show “permission denied” or “invalid token” errors.
Diagnosis:
# Confirm the projected token file is readable without printing its contents
kubectl exec <pod> -- sh -c 'test -r /var/run/secrets/kubernetes.io/serviceaccount/token && echo "token mounted"'
# Check Vault auth method status
kubectl exec -n vault vault-0 -- vault auth list
# Check the role exists
kubectl exec -n vault vault-0 -- vault read auth/kubernetes/role/<role-name>
Mitigation:
- Verify the service account exists and has the correct name
- Check if the Vault role is configured with correct service account name and namespace
- Verify the cluster’s CA cert is configured in Vault’s Kubernetes auth method
- If authentication fails after token rotation, verify the workload rereads its projected token and that its configured audience matches the Vault role.
Prevention:
- Use projected, short-lived service account tokens and confirm workloads handle token rotation
- Monitor Vault auth method configuration for unexpected changes
- Test Kubernetes auth method monthly
Scenario: ESO Sync Failing
Symptoms: ExternalSecret resource exists but Kubernetes Secret is not created. ESO operator logs show errors.
Diagnosis:
# Check ESO operator logs
kubectl logs -n external-secrets deployment/external-secrets-operator
# Check ExternalSecret status
kubectl get externalsecret -n <namespace> -o yaml
# Check secret store connectivity
kubectl get secretstore -n <namespace>
# Verify ESO can reach Vault
kubectl exec -n external-secrets deployment/external-secrets-operator -- curl -s https://vault.example.com/v1/sys/health
Mitigation:
- Verify the SecretStore is configured with the correct Vault address and authentication method.
- Check that the ESO operator has permission to read ExternalSecret and SecretStore resources.
- If the ESO pod restarted recently, wait for reconciliation to complete.
- Delete and recreate the ExternalSecret to trigger a fresh sync.
Prevention:
- Monitor ExternalSecret status with Prometheus metrics
- Set alerts for ESO reconciliation errors
- Use ESO with Vault’s Kubernetes auth method for automatic credential management
Scenario: Database Credentials Not Rotating
Symptoms: Vault shows one set of credentials issued but database shows different user active. Dynamic credentials not being renewed.
Diagnosis:
# Check Vault lease
vault read database/creds/myapp-role
# Check current database users
# For PostgreSQL: SELECT * FROM pg_user;
# Verify lease is being renewed
vault lease list database/
# Check Vault logs for renewal errors
kubectl logs -n vault vault-0 | grep renew
Mitigation:
- If lease expired, Vault automatically revokes credentials; new credentials will be issued on next request
- Services must request new credentials when lease expires; check service implementation
- If using ESO, verify the refresh interval is configured correctly
- Database might have reached max connections due to accumulated stale credentials
Prevention:
- Implement credential refresh logic in services before lease expires
- Monitor lease expiration metrics
- Set database max connections with auto-cleanup for abandoned connections
- Test renewal process in staging
Observability Checklist
- Record the workload identity, secret path, action, result, and time for each access; never record secret values.
- Alert on denied reads, unexpected paths or identities, and unusual access volume.
- Track Vault health, authentication failures, lease renewal and expiry, and External Secrets Operator sync status.
- Confirm rotation reaches each consumer before the old credential is revoked.
- Monitor secret-scanning results and restrict access to any logs or artifacts that may contain exposed values.
- Exercise the response path for a sealed or unavailable store, failed rotation, and missed audit events.
Metrics to Capture
| Metric | What It Tells You | Alert Threshold |
|---|---|---|
vault_secret_access_total |
Secret read rate by path | Unexpected paths accessed |
vault_lease_renewal_success_total |
Dynamic credential renewal success | <99.5% |
vault_lease_expiration_seconds |
Time until dynamic credentials expire | <300s warning, <60s critical |
vault_auth_method_failure_total |
Auth failures by method (k8s, AppRole) | >1% failure rate |
eso_sync_success_total |
External Secrets Operator sync success | <99% |
eso_sync_error_total |
ESO sync errors by type | Any increase |
Logs to Collect
From Vault (structured logging):
{
"event": "secret_accessed",
"client_namespace": "default",
"client_service_account": "payment-service",
"secret_path": "secret/myapp/db-password",
"access_result": "allowed|denied",
"remote_addr": "10.0.0.5",
"timestamp": "2026-03-24T10:30:00Z"
}
{
"event": "lease_renewed",
"lease_id": "database/creds/myapp-role/xyz123",
"ttl_seconds": 3600,
"renewed_by": "spire-agent",
"timestamp": "2026-03-24T10:00:00Z"
}
{
"event": "auth_failure",
"auth_method": "kubernetes",
"client_namespace": "default",
"client_service_account": "unknown-sa",
"failure_reason": "invalid_token|role_not_found|token_expired",
"timestamp": "2026-03-24T10:30:00Z"
}
Key log fields: client identity (namespace, SA), secret path, access result, failure reason, source IP.
Traces to Capture
Enable Vault telemetry with Prometheus metrics. Key metrics to trace:
vault.secret.gen.success: Dynamic secret generation successvault.expire.lease.expiration: Leases approaching expirationvault.auth.kubernetes.fail: Kubernetes auth failures
Dashboards to Build
- Vault Health: Active leases, auth success rate, storage utilization, seal status
- Secret Access Patterns: Read rate by path, top accessed secrets, denied access attempts
- Dynamic Credential Lifecycle: Active credentials by type, expiration heatmap, renewal success rate
- ESO Operations: Sync success rate, error breakdown, reconciliation latency
Alerting Rules
# Vault unavailable
- alert: VaultUnavailable
expr: up{job="vault"} == 0
labels:
severity: critical
annotations:
summary: "Vault is unavailable"
# Vault sealed
- alert: VaultSealed
expr: vault_is_sealed == 1
labels:
severity: critical
annotations:
summary: "Vault is sealed"
# Auth failures
- alert: VaultAuthFailureRate
expr: rate(vault_auth_method_failure_total[5m]) > 0.01
labels:
severity: warning
annotations:
summary: "Vault auth failure rate above 1%"
# Lease expiring soon
- alert: DynamicCredentialExpiring
expr: vault_lease_expiration_seconds < 300
labels:
severity: warning
annotations:
summary: "Dynamic credential expiring in {{ $value }} seconds"
# ESO sync failures
- alert: ESOSyncFailure
expr: rate(eso_sync_error_total[5m]) > 0
labels:
severity: warning
annotations:
summary: "External Secrets Operator sync failures detected"
Security and Compliance Notes
Secrets management sits within a larger security and compliance picture. This section walks through the main security concerns, compliance requirements, and operational practices teams need when managing secrets at scale.
Encryption at Rest Requirements
Managed secrets services encrypt stored values, but teams should verify the configured key, permissions, region, and audit settings for each deployment. Vault encrypts data before writing it to its storage backend; its seal or auto-unseal configuration protects the key material used to unlock the encryption barrier.
For Kubernetes Secrets, the situation is different. etcd stores these unencrypted by default. You need to enable encryption at rest for etcd clusters, lock down RBAC around the Secrets API, and consider external secrets operators that pull from dedicated secrets managers instead of storing secrets directly in etcd. Use AES-GCM encryption instead of the older AESCBC.
Audit Logging for Compliance
Keep audit events that show which workload or operator accessed a secret, which operation they performed, and whether it succeeded. For a SOC 2 review, preserve evidence that supports the controls in scope. Vault audit devices, AWS CloudTrail, and GCP Cloud Audit Logs can record relevant access events; confirm the fields and retention configured in your environment.
For PCI DSS or HIPAA environments, map required events and retention to the systems and data in scope with your compliance lead. Do not assume every secret read is covered automatically. Send the selected logs to a centralized platform and protect them from tampering or unapproved deletion.
Access Control Policies
Least privilege access is foundational to secrets security. In Vault, policies define which paths each role or user can read, write, or manage. A database credentials role should only access database credential paths, nothing else. Vault’s policy language supports glob patterns and capability-based access (read, write, update, delete, list).
Cloud-native secrets services integrate with IAM. GCP Secret Manager uses IAM bindings, AWS Secrets Manager uses resource-based policies alongside IAM, and Azure Key Vault uses access policies with RBAC. Cross-account access should use role assumption with temporary credentials instead of sharing long-lived access keys between accounts.
Secret Rotation Requirements
Regular rotation can shrink the exposure window when a secret is compromised. Requirements depend on the credential, system scope, and applicable standard; for example, PCI DSS has a 90-day password-change rule for certain single-factor user access, with an alternative based on dynamic risk analysis. SOC 2 does not set one universal rotation interval for every secret. Confirm the current control requirements with your compliance lead, then document a schedule and rotate immediately when compromise is suspected. Dynamic secrets expire automatically, while static secrets need a deliberate rotation process.
Automate rotation wherever possible. Manual rotation introduces errors and tends to get postponed. Database passwords should rotate on a schedule using dual-update patterns that keep systems available. API keys rotate through blue-green deployment where new keys activate before old ones revoke. Certificate rotation should use automated cert management like cert-manager for Kubernetes or ACM for AWS, with renewal before expiration.
Credential Isolation Between Services
Each service needs its own credentials. Shared credentials create blast radius problems where one compromised service exposes all services using that credential. A database breach in one service should not give attackers access to databases used by other services. This isolation extends to environments: production credentials should never exist in staging or development, even if they seem internal-only.
Service mesh architectures like Istio and Linkerd provide workload identity at the service level, enabling mTLS without application-level certificate management. Each service gets a cryptographic identity that other services can verify. This complements secrets management by handling both authentication (proving who you are) and authorization (proving what you can access).
Responding to Secrets Compromise
When secrets are compromised, speed matters. The response has four parts: detection and scoping, containment, remediation, and post-incident analysis. Detection figures out which secrets were exposed and for how long. Containment revokes the compromised credential immediately to stop ongoing access. Remediation rotates the credential and redeploys services that used it. Post-incident analysis determines whether the compromise was exploited and what controls failed.
Keep an incident response playbook specifically for secrets compromise scenarios. It should define clear escalation paths, communication templates, and pre-authorized actions that teams can take without waiting for approval during an active incident. It should also define when to bring in external forensic help. For breaches involving regulated data like PHI or payment card data, external forensics may be required for compliance.
Common Pitfalls / Anti-Patterns
- Treating base64 as encryption: Kubernetes Secret values are encoded, not protected by encoding. Configure etcd encryption and narrow RBAC, or use an external store when the cluster’s access model is too broad.
- Sharing one credential across workloads: Give each service its own identity and only the secret paths and actions it needs. Verify the policy denies access to another service’s credentials.
- Rotating before consumers can switch: Fetch the new value, confirm the application has established working connections, then revoke the old credential after the transition window.
- Printing secrets during CI or debugging: Mask output, scan logs and artifacts, and revoke any value that was exposed. Removing a line from the job does not invalidate the credential.
- Keeping a silent fallback when the store is down: Define whether a bounded cache is allowed and when the application must fail closed. Never continue by writing or reading plaintext credentials from an unapproved location.
- Assuming audit logging is healthy because it is enabled: Alert when events stop arriving, and review denied reads, unusual secret paths, auth failures, and lease or sync errors.
Quick Recap Checklist
- Kubernetes Secrets are base64-encoded, not encrypted by default — never store sensitive production data without additional protection
- HashiCorp Vault provides dynamic secrets, fine-grained access policies, and comprehensive audit logging
- Use Vault’s Database secret engine for per-service credentials that expire automatically
- Enable Kubernetes auth method for passwordless pod authentication to Vault
- External Secrets Operator bridges Vault and Kubernetes — secrets sync without application code changes
- Implement graceful credential reload in services to handle rotation without downtime
- Always use least privilege — each service should only access its own secret paths
- Enable Vault audit logging and ship logs to your SIEM for compliance
- Use auto-unseal with cloud KMS (AWS KMS, GCP Cloud KMS, Azure Key Vault) for production
- Monitor Vault health, lease expirations, and ESO sync status with Prometheus alerts
- Never commit secrets to git — use git-secrets, pre-commit hooks, or ESO
- Short-lived credentials reduce blast radius — dynamic secrets expire before attackers can exploit them
- SPIFFE/SPIRE provides workload identity for passwordless service-to-service authentication
- Plan migration from Kubernetes Secrets to Vault early — retrofitting is painful
- Test your incident response playbook for secrets compromise scenarios
Interview Questions
gcloud iam service-accounts keys delete (for GCP) or the equivalent for AWS/Azure. Do not wait — the key is compromised the moment it is public. Second, check CloudTrail or equivalent audit logs for all usage of that key since the commit timestamp — determine if it was actually exploited. Third, revoke all existing keys for that service account and create a new one. Fourth, update any CI/CD pipelines that used the old key with Workload Identity instead. Finally, run a retrospective: why was the key committed — was it in a pre-commit hook, gitignore misconfiguration, or IDE accident?
Further Reading
- Encryption at Rest — Understand storage encryption and the role of key management.
- Access Control Models and Least Privilege — Apply narrow, reviewable permissions to people and workloads.
- Kubernetes ConfigMaps and Secrets — Compare Kubernetes configuration objects and their security controls.
- Service Identity — Explore workload identity and authentication without shared credentials.
- HashiCorp Vault Documentation — Official documentation for secret engines, authentication, and operations.
- Kubernetes Secrets Documentation — Kubernetes Secret objects, encryption configuration, and access controls.
- External Secrets Operator — Project documentation for syncing secrets from external stores into Kubernetes.
- OWASP Secrets Management Cheat Sheet — Practical guidance on secret storage, access, and rotation.
- PCI SSC FAQ 1590 — Scope and alternatives for PCI DSS password-change requirements.
Conclusion
Secrets management connects to several other patterns worth understanding.
mTLS and Service Mesh handles encryption and authentication of service-to-service communication. Service meshes often leverage workload identity to issue short-lived certificates automatically.
Kubernetes provides the container orchestration layer where many secrets management solutions run. Understanding Kubernetes RBAC and service accounts is foundational.
GitOps changes how you think about configuration management. Secrets become part of the reconciliation loop without living in git.
Service Identity and SPIFFE provides the cryptographic identity layer that enables passwordless authentication and short-lived credentials.
Kubernetes Secrets can be a reasonable starting point for small deployments when etcd encryption and RBAC are configured. As services and teams grow, Vault or a cloud secrets manager can add per-workload credentials, rotation, and audit trails. Test credential refresh and incident procedures before relying on them in production.
Category
Related Posts
Kubernetes Network Policies: Practical Pod Security
Implement microsegmentation in Kubernetes using Network Policies to control traffic flow between pods and enforce zero-trust networking.
GitOps: Infrastructure as Code with Git for Microservices
Learn the GitOps operating model, reconciliation loop, repository patterns, secret boundaries, and trade-offs for Kubernetes deployments.
Health Checks: Liveness, Readiness, and Service Availability
Master health check implementation for microservices including liveness probes, readiness probes, and graceful degradation patterns.