Lesson 16 of 20 · Practice: Vault, egress and tenant labs
Vault on Kubernetes: login, delivery and rotation
Connect HashiCorp Vault to Kubernetes properly: pods log in with their ServiceAccount token, a role maps namespace + ServiceAccount to a policy, and secrets arrive through the Agent Injector, the CSI provider or the Vault Secrets Operator. Then store, update and roll back a password in KV v2, and harden the setup.
Open the lab on GitHubthe companion repo has this guide as guides/vault.md
Where this lesson fits
Secrets management (lesson 11) covers the basics: encrypting Secrets in etcd, keeping them out of Git, External Secrets. This lesson goes one level deeper on the most common external store, HashiCorp Vault: how a pod proves who it is to Vault, the three ways secrets reach the pod, and how to change a password without breaking anyone.
pod (ServiceAccount token, audience "vault")
│ 1. login: "I am payments/payments-api"
▼
Vault ── 2. TokenReview ──► Kubernetes API: "is this token real, and whose is it?"
│ 3. role payments-api → policy payments-api → Vault token (20 min)
▼
4. read kv/payments/api/*, database/creds/payments-ro
│
▼ delivered by: Agent Injector · CSI provider · Vault Secrets Operator
the app reads a file or an env var
A hotel guest (the pod) shows the key card the hotel gave them (the ServiceAccount token) at the safe-deposit desk (Vault). The desk phones reception (the Kubernetes API) to check the card is real and which room it belongs to, then opens only the boxes that room is allowed to open, and only for 20 minutes.
1. Decide the architecture first
| Decision | Options | Sensible default |
|---|---|---|
| Where Vault runs | Same cluster, a dedicated cluster or VMs, or a managed service | Outside the workload clusters: a compromised workload cluster can't reach Vault's storage, and one Vault serves many clusters |
| Storage and HA | Integrated storage (Raft), Consul | Raft, 3 or 5 nodes across failure domains, scheduled snapshots |
| Unseal | Shamir key shares, or auto-unseal (cloud KMS, HSM, Transit) | Auto-unseal. Air-gapped sites: an HSM, or a small Vault running Transit just for unseal |
| How pods log in | kubernetes auth (TokenReview) or jwt auth (OIDC discovery / JWKS) |
kubernetes by default; jwt when Vault can't reach the API server |
| How secrets arrive | Agent Injector, CSI provider, Vault Secrets Operator, or the app calls Vault itself | See section 4 |
Licence
Since 2023 Vault is under the Business Source Licence. OpenBao is the open-source (MPL) fork under the Linux Foundation, with a compatible API and Kubernetes integrations. Everything in this lesson works the same way on both; check each project's docs for the exact Helm chart names.
2. Install with Helm
helm repo add hashicorp https://helm.releases.hashicorp.com
helm repo update
# Vault itself in Kubernetes, HA with Raft, plus the injector
helm install vault hashicorp/vault -n vault --create-namespace \
--set server.ha.enabled=true --set server.ha.raft.enabled=true \
--set server.ha.replicas=3 --set injector.enabled=true
# OR: a workload cluster that uses an EXTERNAL Vault: only the injector, no server
helm install vault hashicorp/vault -n vault --create-namespace \
--set global.externalVaultAddr=https://vault.example.com:8200 \
--set server.enabled=false --set injector.enabled=true
Initialise once (vault operator init), or let auto-unseal handle it. Keep the recovery keys offline, split between several people.
3. Let pods log in: the Kubernetes auth method
One auth mount per cluster keeps clusters apart (k8s-prod, k8s-dev):
vault auth enable -path=k8s-prod kubernetes
# Vault OUTSIDE the cluster: API address, cluster CA, and a token allowed to call TokenReview
vault write auth/k8s-prod/config \
kubernetes_host="https://api.prod.example.com:6443" \
kubernetes_ca_cert=@ca.crt \
token_reviewer_jwt="$(kubectl create token vault-reviewer -n vault --duration=8760h)"
The vault-reviewer ServiceAccount needs the built-in ClusterRole system:auth-delegator, which allows TokenReview. (Alternative: leave out token_reviewer_jwt and give system:auth-delegator to each client ServiceAccount; Vault then uses the client's own token for the review.) When Vault runs inside the cluster, it can use its own pod's token and CA, so kubernetes_host is enough.
Now a policy (what may be read) and a role (who gets that policy):
vault policy write payments-api - <<'EOF'
path "kv/data/payments/api/*" { capabilities = ["read"] }
path "database/creds/payments-ro" { capabilities = ["read"] }
EOF
vault write auth/k8s-prod/role/payments-api \
bound_service_account_names=payments-api \
bound_service_account_namespaces=payments \
audience=vault \
token_policies=payments-api \
token_ttl=20m token_max_ttl=1h
Three common mistakes
bound_service_account_names=*withbound_service_account_namespaces=*: every pod in the cluster gets the role.- No
audience: a token stolen from somewhere else in the cluster can be replayed against Vault. Withaudience=vault, only tokens minted for Vault work. - A
token_reviewer_jwtthat lives for years and is never rotated.
Secrets engines worth knowing:
- KV v2: static secrets with versions. The API path contains
data/(kv/data/payments/db); the CLI adds it for you. - Database: a fresh username and password per pod, with a lease. Revoke the lease and the access is gone. This is the biggest win over a shared static password.
- PKI: short-lived TLS certificates, also usable from cert-manager's Vault issuer (cert-manager in production).
- Transit: encryption as a service; the app never holds the key. It can also act as the KMS behind etcd encryption at rest.
4. Choose how secrets reach the pod
| Agent Injector | CSI provider | Vault Secrets Operator (VSO) | |
|---|---|---|---|
| How | A mutating webhook adds a vault-agent init container and sidecar | The Secrets Store CSI driver mounts a tmpfs volume | A controller copies Vault data into normal Kubernetes Secrets |
| Secret stored in etcd? | No | No (unless you turn on sync to Secrets) | Yes, so encryption at rest is a must |
| Dynamic secrets and renewal | Yes, with templates | Fetched at mount; updates need the driver's rotation feature | Yes, and it can restart the workload |
| Cost | A sidecar in every pod | A DaemonSet on every node | One controller |
| Good for | Dynamic database credentials, templated config files | "Never in etcd" rules, simple static secrets | GitOps teams, apps that expect a Secret |
Agent Injector
apiVersion: apps/v1
kind: Deployment
metadata: { name: payments-api, namespace: payments }
spec:
selector: { matchLabels: { app: payments-api } }
template:
metadata:
labels: { app: payments-api }
annotations:
vault.hashicorp.com/agent-inject: "true"
vault.hashicorp.com/auth-path: "auth/k8s-prod"
vault.hashicorp.com/role: "payments-api"
vault.hashicorp.com/agent-inject-secret-db.env: "database/creds/payments-ro"
vault.hashicorp.com/agent-inject-template-db.env: |
{{- with secret "database/creds/payments-ro" -}}
DB_USER={{ .Data.username }}
DB_PASS={{ .Data.password }}
{{- end }}
spec:
serviceAccountName: payments-api
containers:
- name: api
image: registry.example.com/payments-api@sha256:... # the file appears at /vault/secrets/db.env
CSI provider
helm install csi secrets-store-csi-driver/secrets-store-csi-driver -n kube-system
helm upgrade vault hashicorp/vault -n vault --reuse-values --set csi.enabled=true
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata: { name: payments-vault, namespace: payments }
spec:
provider: vault
parameters:
vaultAddress: "https://vault.example.com:8200"
roleName: "payments-api"
vaultKubernetesMountPath: "k8s-prod"
objects: |
- objectName: "api-key"
secretPath: "kv/data/payments/api/config"
secretKey: "api_key"
The pod then mounts a csi volume with driver: secrets-store.csi.k8s.io and secretProviderClass: payments-vault.
Vault Secrets Operator
apiVersion: secrets.hashicorp.com/v1beta1
kind: VaultAuth
metadata: { name: payments-auth, namespace: payments }
spec:
vaultConnectionRef: prod-vault # a VaultConnection with the address and CA
method: kubernetes
mount: k8s-prod
kubernetes: { role: payments-api, serviceAccount: payments-api, audiences: ["vault"] }
---
apiVersion: secrets.hashicorp.com/v1beta1
kind: VaultStaticSecret
metadata: { name: api-config, namespace: payments }
spec:
vaultAuthRef: payments-auth
type: kv-v2
mount: kv
path: payments/api/config
refreshAfter: 60s
destination: { name: api-config, create: true }
rolloutRestartTargets:
- { kind: Deployment, name: payments-api }
VSO feels like the External Secrets Operator from lesson 11. Pick one of the two per cluster, not both.
5. Store, change and roll back a password (KV v2)
export VAULT_ADDR=https://vault.example.com:8200 VAULT_CACERT=/path/ca.crt
vault login -method=oidc
vault secrets enable -path=kv kv-v2
vault kv put -mount=kv payments/db username=app_user password=@/dev/stdin <<< "$PW" # keeps it out of shell history
vault kv patch -mount=kv payments/db password=@/dev/stdin <<< "$NEW_PW" # change ONE field
vault kv put -mount=kv -cas=3 payments/db username=u2 password=p2 # write only if the current version is 3
vault kv metadata get -mount=kv payments/db # versions
vault kv rollback -mount=kv -version=2 payments/db
put replaces, patch changes
vault kv put writes a whole new version: any field you leave out is gone. Use patch to change one field, and -cas (check-and-set) so two people can't overwrite each other.
Who may write: the app's policy is read-only; only an admin or the pipeline gets create, update and patch on kv/data/payments/db and read/list on kv/metadata/payments/db.
How the change reaches running pods:
| Delivery | After an update |
|---|---|
| Vault Secrets Operator | Re-reads every refreshAfter, updates the Secret, restarts the workload via rolloutRestartTargets |
| Agent Injector | Re-renders the file; the app must re-read it, or be restarted |
| CSI provider | Only if rotation is turned on in the CSI driver; otherwise at the next pod start |
For databases, prefer the database engine: every pod gets its own short-lived login and nobody rotates a password by hand.
6. Harden it
- TLS everywhere; clients pin Vault's CA. Never
tls_skip_verify. - Auto-unseal, recovery keys split among several people, root token revoked after setup.
- One role per workload, bound to namespace + ServiceAccount + audience; policies no wider than one app's paths.
- Short TTLs, dynamic secrets wherever the backend supports them.
- Two audit devices (for example file and syslog). Vault stops answering if it can't write to any audit device, so one broken disk shouldn't stop production. Values in the audit log are hashed, not plain text.
- Network: a NetworkPolicy so only the namespaces that need Vault (or the injector and CSI pods) reach port 8200.
- Injector resilience: 2+ replicas and a PodDisruptionBudget, with its
failurePolicyand namespace selector chosen on purpose, so a Vault outage doesn't block every deployment (Pod Security & admission control explains webhook failure modes). - Operations: Raft snapshots copied off-site and restore-tested; metrics into Prometheus.
- Air-gapped: mirror the Vault, injector and CSI provider images and charts into your registry, pin versions, unseal with an HSM or Transit.
7. Prove it works
# a token made for Vault logs in
kubectl -n payments create token payments-api --audience=vault --duration=10m > /tmp/jwt
vault write auth/k8s-prod/login role=payments-api jwt=@/tmp/jwt
# the agent rendered the file
kubectl -n payments exec deploy/payments-api -c api -- cat /vault/secrets/db.env
# negative test: another ServiceAccount must be refused
kubectl -n payments create token default --audience=vault | vault write auth/k8s-prod/login role=payments-api jwt=-
The last command must fail with permission denied. If it succeeds, your role's bindings are too wide.
Try it: Vault in dev mode on kind
- On a kind cluster, install the chart with
--set server.dev.enabled=true --set injector.enabled=true(dev mode: in memory, unsealed, for practice only). - Enable
kubernetesauth atk8s-dev, write thepayments-apipolicy and role from section 3, and a KV v2 secret. - Deploy a small pod with the injector annotations and read
/vault/secrets/.... - Run the negative test from section 7 with the
defaultServiceAccount. - Change the password with
vault kv patch, then watch what the file in the pod does, and what your app would need to do.
Going deeper
- Cloud clusters can skip static cloud keys entirely: see Cloud workload identity.
- For workload-to-workload identity rather than secrets, see Workload identity with SPIFFE.
- Response-wrapping hands a secret over once, so a copied hand-off token is useless after first use.
Recap
- Pods log in with their ServiceAccount token; a Vault role maps namespace + ServiceAccount + audience to a policy.
- Three delivery patterns: Agent Injector (sidecar, dynamic), CSI (volume, never in etcd), VSO (Kubernetes Secrets, needs encryption at rest).
- KV v2:
putreplaces,patchchanges one field,-casprevents lost updates, every write is a version. - Prefer dynamic database credentials, short TTLs, two audit devices, and Vault outside the workload clusters.
This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.