Skip to main content

Managing Kubernetes Secrets with Vault

Manage Kubernetes Secrets and ConfigMaps securely with encryption at rest, RBAC, and HashiCorp Vault injection, plus rotation and GitOps options.

52 Terms

Overview and What You Will Learn

Kubernetes Secrets hold sensitive values such as passwords and API keys, and ConfigMaps hold non-sensitive configuration. A Secret is only base64 encoded by default, which is encoding and not encryption, so real protection comes from encryption at rest in etcd, tight access control, and, for stronger guarantees, an external manager such as HashiCorp Vault that issues short-lived credentials and keeps an audit log.

In this lab you will create and consume Secrets and ConfigMaps, turn on encryption at rest, lock down who can read Secrets, deploy Vault in high-availability mode, and inject secrets into a pod with the Vault Agent.

By the end you will be able to:

  • Create Secrets without leaving values in manifests or Git, and consume them as files or environment variables
  • Separate non-sensitive configuration into ConfigMaps and reload it safely
  • Enable encryption at rest for Secrets in etcd
  • Explain what Kubernetes RBAC does and does not protect on Secrets
  • Deploy Vault on Kubernetes with integrated storage, and inject secrets with Kubernetes authentication
  • Choose between native Secrets, External Secrets Operator, Sealed Secrets, and Vault

Why This Matters in Production

A leaked credential is one of the fastest routes from a small mistake to a large incident. Passwords hardcoded in images, in Deployment YAML, or in environment variables committed to Git are found by automated scanners within minutes of becoming public, and one database credential can expose every record behind it.

For platforms that handle payments and trading, such as Stripe, Razorpay, or Zerodha, credential handling is also a compliance topic, because auditors ask who could read a secret and when it was last rotated. The goal of this guide is that no secret lives in an image or a repository, every access is authorized and logged, and credentials expire on their own.

Core Principles

Every value your app needs falls into one of two groups, and each group gets a different tool. Non-sensitive settings go in a ConfigMap. Sensitive values go in a Secret, and in an external manager when you need rotation, dynamic credentials, or an audit trail.

Option Best For Trade-off
Kubernetes Secret Small teams, simple needs Static values, manual rotation
External Secrets Operator Teams on a cloud secret manager Syncs into Secrets, so values land in etcd
Sealed Secrets or SOPS Committing encrypted secrets to Git Static values, key management
Vault Compliance, rotation, dynamic secrets Extra system to run and secure

Rules that apply to all options:

  1. Never put sensitive values in a ConfigMap. They are plain text and visible to anyone who can read it.
  2. Never commit a plain Secret manifest to Git. Use sealed, encrypted, or externally sourced secrets.
  3. Prefer mounted files over environment variables. Environment variables are easy to leak through logs, crash dumps, and child processes, and they do not update without a restart.
  4. Enable encryption at rest for the secrets resource.
  5. Restrict who can read Secrets through the API, and who can create pods in a namespace.
  6. Rotate on a schedule, and immediately when a person with access leaves.

The Vault Agent injector gives each pod a sidecar that logs in to Vault with the pod's service account token, fetches the secrets it is allowed to read, and writes them to an in-memory file for the app.

sequenceDiagram participant A as Vault Agent participant V as Vault participant K as Kubernetes API participant P as App container A->>V: Login with SA token V->>K: Validate token K-->>V: Token is valid V-->>A: Vault token and policy A->>V: Read secret path V-->>A: Secret data A->>P: Write /vault/secrets file

Detailed Step-by-Step Practical Lab

Step 1 - Create a Secret Without Putting Values in a File

kubectl create secret builds the object directly, so no manifest with credentials needs to exist or be committed. Generate the password instead of typing a memorable one, and remember that shell history and process lists can record literals.

Bash
kubectl create namespace production
export DB_PASSWORD="$(openssl rand -base64 24)"
kubectl create secret generic db-credentials \
--from-literal=DB_HOST=10.0.1.50 \
--from-literal=DB_NAME=trading_prod \
--from-literal=DB_USER=rahul \
--from-literal=DB_PASSWORD="$DB_PASSWORD" \
-n production
unset DB_PASSWORD
kubectl describe secret db-credentials -n production
Remember

Base64 is trivially reversible, with kubectl get secret db-credentials -n production -o jsonpath='{.data.DB_PASSWORD}' | base64 --decode. Anyone who can get the Secret can read the value, so the protection comes from access control and encryption, not from the encoding.

Step 2 - Consume Secrets as Files or Environment Variables

Mounted files are the safer default. They can be given restrictive permissions, they update when the Secret changes (unless mounted with subPath), and they do not show up in the process environment. Use secretKeyRef to inject only the keys the app needs if you must use environment variables.

YAML
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: trading-api
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: trading-api
template:
metadata:
labels:
app: trading-api
spec:
serviceAccountName: trading-api-sa
containers:
- name: trading-api
image: registry.razorpay.in/trading-api:v4.2.1
env:
- name: DB_HOST
valueFrom:
secretKeyRef:
name: db-credentials
key: DB_HOST
volumeMounts:
- name: db-secret
mountPath: /etc/secrets/db
readOnly: true
- name: tls-certs
mountPath: /etc/ssl/app
readOnly: true
volumes:
- name: db-secret
secret:
secretName: db-credentials
defaultMode: 0400 # readable by the owner only
- name: tls-certs
secret:
secretName: trading-tls # holds tls.crt and tls.key
defaultMode: 0400
Security

Set defaultMode on secret volumes so private keys are not world-readable inside the container, and set readOnly: true on the mount. Also run the container as a non-root user and set fsGroup if the app needs group access.

Step 3 - Keep Non-Sensitive Settings in a ConfigMap

A ConfigMap carries settings that are safe to read, either as environment variables or as files. Mark stable ones immutable: true, which protects against accidental edits and reduces API server load.

YAML
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
namespace: production
data:
LOG_LEVEL: info
APP_ENV: production
PORT: "8080"
limits.yaml: |
maxOrdersPerSecond: 200
marketOpen: "09:15"

Consume it next to the Secret in the container spec:

YAML
envFrom:
- configMapRef:
name: app-config
volumeMounts:
- name: app-config-files
mountPath: /etc/app
volumes:
- name: app-config-files
configMap:
name: app-config
items:
- key: limits.yaml
path: limits.yaml

How changes reach the pod matters for reload:

  1. Environment variables: read once at container start, so a restart is required.
  2. Mounted files: updated in place after a short delay (up to about a minute), unless you used subPath. The app must re-read the file.
  3. Rolling restart on change: add a checksum of the ConfigMap as a pod annotation in Helm, or use a controller such as Stakater Reloader, so a change triggers a new rollout.
Step 4 - Enable Encryption at Rest for Secrets in etcd

By default, Secrets are stored unencrypted in etcd, so anyone who can read etcd or its backups can read every Secret. On managed clusters, turn on the provider's feature that encrypts Secrets with a KMS key you control, such as envelope encryption on EKS or application-layer secrets encryption on GKE. On a self-managed control plane you configure the API server yourself.

The strongest option is a KMS provider (v2), where the encryption key lives outside the cluster. Without one, secretbox is the recommended local provider. Avoid aescbc for new setups. List the encrypting provider first, because the first provider is used for writes, and keep identity last until every Secret has been rewritten.

YAML
# /etc/kubernetes/encryption-config.yaml on each control plane node
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources:
- secrets
providers:
- secretbox:
keys:
- name: key1
secret: <base64-encoded-32-byte-key>
- identity: {} # lets existing unencrypted Secrets still be read
Bash
# Generate a 32-byte key and keep it out of Git
head -c 32 /dev/urandom | base64

Add the flag --encryption-provider-config=/etc/kubernetes/encryption-config.yaml to the kube-apiserver manifest, and also add a hostPath volume and volumeMount so the file is visible inside the API server pod. Then rewrite existing Secrets so they are stored encrypted, and verify directly in etcd.

Bash
# Re-write all Secrets so they are saved with the new provider
kubectl get secrets --all-namespaces -o json | kubectl replace -f -
# Verify: the stored value should start with the provider prefix, not plain text
ETCDCTL_API=3 etcdctl \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key \
get /registry/secrets/production/db-credentials | hexdump -C | head
# Look for: k8s:enc:secretbox:v1:key1
Remember

Encryption at rest protects etcd and its backups. It does not stop an authorized API user from reading a Secret, so RBAC is still required. To rotate the key, add the new key at the top of the list, restart the API servers, rewrite all Secrets, then remove the old key.

Step 5 - Control Who Can Read Secrets

RBAC decides who can read Secrets through the Kubernetes API, which covers people, CI jobs, and controllers. Grant get on specific Secrets by name. Avoid list and watch on Secrets, because a list response contains the secret values.

YAML
apiVersion: v1
kind: ServiceAccount
metadata:
name: trading-api-sa
namespace: production
YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: trading-api-secret-reader
namespace: production
rules:
- apiGroups: [""]
resources: ["secrets"]
resourceNames: ["db-credentials"]
verbs: ["get"]
YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: trading-api-secret-binding
namespace: production
subjects:
- kind: ServiceAccount
name: trading-api-sa
namespace: production
roleRef:
kind: Role
name: trading-api-secret-reader
apiGroup: rbac.authorization.k8s.io
Bash
kubectl auth can-i get secret/db-credentials \
--as=system:serviceaccount:production:trading-api-sa -n production
# yes
kubectl auth can-i list secrets \
--as=system:serviceaccount:production:trading-api-sa -n production
# no
Common Mistake

Assuming a pod's service account RBAC controls which Secrets that pod can mount. The kubelet reads the Secret on the pod's behalf, so mounting is not checked against the service account. Anyone who can create pods in a namespace can mount every Secret in it. Limit who can create pods, give each team its own namespace, and use admission policies for sensitive namespaces.

Step 6 - Deploy Vault in High-Availability Mode

The Helm chart needs server.ha.raft.enabled=true to use integrated Raft storage, otherwise HA mode expects an external storage backend. The chart also installs the Agent Injector webhook by default.

Bash
helm repo add hashicorp https://helm.releases.hashicorp.com
helm repo update
helm install vault hashicorp/vault \
--namespace vault --create-namespace \
--set server.ha.enabled=true \
--set server.ha.raft.enabled=true \
--set server.ha.replicas=3 \
--set server.dataStorage.size=10Gi
kubectl get pods -n vault
# vault-0 0/1 Running 0 <- not ready until initialised and unsealed

Initialise once, then unseal the first node. Vault starts sealed, and unsealing requires a threshold of key shares. The other two nodes must join the Raft cluster and be unsealed too.

Bash
kubectl exec -n vault vault-0 -- vault operator init \
-key-shares=5 -key-threshold=3 -format=json > vault-init.json
# Unseal vault-0 with three different keys from vault-init.json
kubectl exec -n vault vault-0 -- vault operator unseal <unseal-key-1>
kubectl exec -n vault vault-0 -- vault operator unseal <unseal-key-2>
kubectl exec -n vault vault-0 -- vault operator unseal <unseal-key-3>
# Join and unseal the other nodes
kubectl exec -n vault vault-1 -- vault operator raft join http://vault-0.vault-internal:8200
kubectl exec -n vault vault-2 -- vault operator raft join http://vault-0.vault-internal:8200
# Then run the three unseal commands on vault-1 and vault-2 as well
Security

The init output holds the unseal keys and the root token. Distribute the key shares to different people, store them outside the cluster and outside Git, and delete vault-init.json. For production, configure auto-unseal with a cloud KMS so restarts do not need humans, enable TLS on Vault, and revoke the root token after creating scoped admin policies.

Step 7 - Configure Kubernetes Authentication, a Secrets Engine, and a Policy

Open a shell in the Vault pod and log in with the root token for this one-time setup. The KV version 2 secrets engine must be enabled explicitly outside dev mode. Policies for KV v2 use the secret/data/... path.

Bash
kubectl exec -n vault -it vault-0 -- /bin/sh
Bash
# Inside the pod
vault login
vault auth enable kubernetes
vault write auth/kubernetes/config \
kubernetes_host="https://$KUBERNETES_PORT_443_TCP_ADDR:443"
vault secrets enable -path=secret kv-v2
vault kv put secret/production/trading-api \
db_password="$(head -c 24 /dev/urandom | base64)" \
api_key="demo-api-key-not-real" \
jwt_secret="$(head -c 32 /dev/urandom | base64)"
vault policy write trading-api-policy - <<EOF
path "secret/data/production/trading-api" {
capabilities = ["read"]
}
EOF
vault write auth/kubernetes/role/trading-api \
bound_service_account_names=trading-api-sa \
bound_service_account_namespaces=production \
policies=trading-api-policy \
ttl=1h

The role binds a service account name and namespace to a policy, so only pods running as trading-api-sa in production can log in and read that one path.

Step 8 - Inject Secrets into the Pod with the Vault Agent

Annotations on the pod template tell the injector to add the Agent. Put them under spec.template.metadata, not on the Deployment itself. The template renders the secret to /vault/secrets/config, an in-memory volume shared with your container.

YAML
# deployment-vault.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: trading-api
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: trading-api
template:
metadata:
labels:
app: trading-api
annotations:
vault.hashicorp.com/agent-inject: "true"
vault.hashicorp.com/role: "trading-api"
vault.hashicorp.com/agent-inject-secret-config: "secret/data/production/trading-api"
vault.hashicorp.com/agent-inject-template-config: |
{{- with secret "secret/data/production/trading-api" -}}
export DB_PASSWORD="{{ .Data.data.db_password }}"
export API_KEY="{{ .Data.data.api_key }}"
export JWT_SECRET="{{ .Data.data.jwt_secret }}"
{{- end }}
spec:
serviceAccountName: trading-api-sa
containers:
- name: trading-api
image: registry.razorpay.in/trading-api:v4.2.1
command: ["/bin/sh", "-c"]
args: ["source /vault/secrets/config && exec node server.js"]
Bash
kubectl apply -f deployment-vault.yaml
kubectl get pods -n production
# trading-api-6d9f7c-xk2pq 2/2 Running <- app plus vault-agent
kubectl exec -n production deploy/trading-api -c trading-api -- ls /vault/secrets

The Agent keeps renewing its token and re-renders the file when the secret changes. The app still has to re-read it, or be restarted, to pick up a new value. If you would rather keep Kubernetes Secrets as the interface, the Vault Secrets Operator or the Secrets Store CSI Driver can sync Vault data for you.

Step 9 - Use Dynamic Database Credentials

Static values in KV still need manual rotation. Vault's database engine creates a unique, short-lived database user for each request, so a leaked credential expires by itself. This outline assumes a PostgreSQL database at 10.0.1.50 and an admin account Vault can use.

Bash
vault secrets enable database
vault write database/config/trading-db \
plugin_name=postgresql-database-plugin \
allowed_roles=trading-api \
connection_url="postgresql://{{username}}:{{password}}@10.0.1.50:5432/trading_prod" \
username="vault_admin" password="<vault-admin-password>"
vault write database/roles/trading-api \
db_name=trading-db \
creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}'; GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA public TO \"{{name}}\";" \
default_ttl=1h max_ttl=24h
vault read database/creds/trading-api

Extend the policy with path "database/creds/trading-api" { capabilities = ["read"] }, and point the injector annotation at that path. Revoke a leaked credential immediately with vault lease revoke <lease-id>.

Production Best Practices & Common Pitfalls

  • Use External Secrets Operator when you already run a cloud secret manager. It syncs from AWS Secrets Manager or GCP Secret Manager into Kubernetes Secrets, though the values then also exist in etcd, so encryption at rest still matters.
  • Use Sealed Secrets or SOPS for GitOps. Only encrypted manifests belong in a repository, and the decryption key stays in the cluster or a KMS.
  • Scan for leaks. Run a secret scanner in CI and as a pre-commit hook, and rotate anything that was ever committed, since deleting the commit does not remove it from history.
  • Audit access. Enable Kubernetes audit logging for secrets and Vault audit devices, and alert on reads by unexpected identities.
  • Rotate on a schedule and on departures. Dynamic secrets with short TTLs make this automatic.
  • Do not print Secrets. Avoid kubectl get secret -o yaml on shared or recorded screens, since the values decode in one step.
  • Prefer named keys over whole-secret injection. envFrom: secretRef exposes every key in the Secret, including ones the app does not need.
Common Mistake

Putting the Vault annotations on the Deployment's own metadata instead of spec.template.metadata. The injector reads annotations from the pod, so no sidecar is added and the pod starts with no secrets.

Quick Reference & Troubleshooting Commands

Command Purpose
kubectl create secret generic <name> --from-literal=KEY=VALUE -n <ns> Create a Secret
kubectl describe secret <name> -n <ns> List keys without values
kubectl auth can-i get secret/<name> --as=system:serviceaccount:<ns>:<sa> -n <ns> Test service account access
kubectl get secrets --all-namespaces -o json | kubectl replace -f - Rewrite Secrets after enabling encryption
vault kv get secret/production/trading-api Read a KV secret
vault operator raft list-peers Show Raft cluster members
vault lease revoke <lease-id> Revoke a dynamic credential
vault lease revoke -prefix database/creds/trading-api Revoke all credentials for a role
kubectl get externalsecrets -n <ns> List External Secrets Operator syncs
Symptom Likely Cause Fix
Pod has no vault-agent container Annotations on the wrong object Move them under spec.template.metadata
Vault login returns permission denied Role does not match service account or namespace Check bound_service_account_* on the role
Vault pods stay 0/1 Not initialised or still sealed Run vault operator init and unseal
vault-1 will not join Raft join not run Run vault operator raft join against vault-0
Secret in etcd readable as plain text Provider order or flag missing Put the encrypting provider first and rewrite Secrets
Forbidden on get secret RBAC rule missing or wrong name Check the Role resourceNames
ConfigMap change not visible Environment variable or subPath mount Restart the pod or mount as a normal file volume

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Security and Access Control

All 3 Topics

Frequently Asked Questions

Is Managing Kubernetes Secrets with Vault free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Managing Kubernetes Secrets with Vault topic cover?

Manage Kubernetes Secrets and ConfigMaps securely with encryption at rest, RBAC, and HashiCorp Vault injection, plus rotation and GitOps options.

Found a mistake, an outdated step or a broken link?