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:
- Never put sensitive values in a ConfigMap. They are plain text and visible to anyone who can read it.
- Never commit a plain Secret manifest to Git. Use sealed, encrypted, or externally sourced secrets.
- 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.
- Enable encryption at rest for the
secretsresource. - Restrict who can read Secrets through the API, and who can create pods in a namespace.
- 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.
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.
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 productionRememberBase64 is trivially reversible, with
kubectl get secret db-credentials -n production -o jsonpath='{.data.DB_PASSWORD}' | base64 --decode. Anyone who cangetthe 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.
# deployment.yamlapiVersion: apps/v1kind: Deploymentmetadata: name: trading-api namespace: productionspec: 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: 0400SecuritySet
defaultModeon secret volumes so private keys are not world-readable inside the container, and setreadOnly: trueon the mount. Also run the container as a non-root user and setfsGroupif 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.
apiVersion: v1kind: ConfigMapmetadata: name: app-config namespace: productiondata: 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:
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.yamlHow changes reach the pod matters for reload:
- Environment variables: read once at container start, so a restart is required.
- 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. - 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.
# /etc/kubernetes/encryption-config.yaml on each control plane nodeapiVersion: apiserver.config.k8s.io/v1kind: EncryptionConfigurationresources: - resources: - secrets providers: - secretbox: keys: - name: key1 secret: <base64-encoded-32-byte-key> - identity: {} # lets existing unencrypted Secrets still be read# Generate a 32-byte key and keep it out of Githead -c 32 /dev/urandom | base64Add 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.
# Re-write all Secrets so they are saved with the new providerkubectl get secrets --all-namespaces -o json | kubectl replace -f - # Verify: the stored value should start with the provider prefix, not plain textETCDCTL_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:key1RememberEncryption 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.
apiVersion: v1kind: ServiceAccountmetadata: name: trading-api-sa namespace: productionapiVersion: rbac.authorization.k8s.io/v1kind: Rolemetadata: name: trading-api-secret-reader namespace: productionrules: - apiGroups: [""] resources: ["secrets"] resourceNames: ["db-credentials"] verbs: ["get"]apiVersion: rbac.authorization.k8s.io/v1kind: RoleBindingmetadata: name: trading-api-secret-binding namespace: productionsubjects: - kind: ServiceAccount name: trading-api-sa namespace: productionroleRef: kind: Role name: trading-api-secret-reader apiGroup: rbac.authorization.k8s.iokubectl 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# noCommon MistakeAssuming 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.
helm repo add hashicorp https://helm.releases.hashicorp.comhelm 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 unsealedInitialise 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.
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.jsonkubectl 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 nodeskubectl exec -n vault vault-1 -- vault operator raft join http://vault-0.vault-internal:8200kubectl 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 wellSecurityThe 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.
kubectl exec -n vault -it vault-0 -- /bin/sh# Inside the podvault login vault auth enable kubernetesvault 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 - <<EOFpath "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=1hThe 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.
# deployment-vault.yamlapiVersion: apps/v1kind: Deploymentmetadata: name: trading-api namespace: productionspec: 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"]kubectl apply -f deployment-vault.yamlkubectl 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/secretsThe 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.
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-apiExtend 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
secretsand 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 yamlon shared or recorded screens, since the values decode in one step. - Prefer named keys over whole-secret injection.
envFrom: secretRefexposes every key in the Secret, including ones the app does not need.
Common MistakePutting the Vault annotations on the Deployment's own
metadatainstead ofspec.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 |