Skip to content

Deploying Vault Agent Injector on Kubernetes for annotation-driven secrets

Install the HashiCorp Vault Agent Injector on a Kubernetes cluster and inject secrets into pods through annotations — no Kubernetes Secret objects, short-lived tokens, automatic renewal.

You’re running a workload on Kubernetes that needs a short-lived database credential renewed every 30 minutes, a TLS keypair rotated weekly, and an OAuth client secret that the security team insists must never live in a Kubernetes Secret object — because the cluster auditor can read every Secret in every namespace. Materializing those into long-lived Secrets defeats the purpose. The pattern that fits is a sidecar that authenticates with the pod’s ServiceAccount, fetches the secret from Vault, writes it to a tmpfs volume the application reads, and renews it before it expires.

What’s happening

The Vault Agent Injector is a Kubernetes mutating admission webhook (vault-k8s) that watches for pods carrying vault.hashicorp.com/agent-inject: "true" and rewrites them on admission to add a Vault Agent sidecar (or init container) and a shared emptyDir volume mounted at /vault/secrets. The agent authenticates to Vault using the Kubernetes auth method — it sends the pod’s ServiceAccount JWT to Vault, Vault verifies it with the cluster’s TokenReview API, and returns a short-lived Vault token scoped to a Vault role you’ve defined. The agent then reads the secrets the annotations specify, renders them into files via Go templates, and renews them on a schedule. The pod’s main container reads /vault/secrets/<name>. No Kubernetes Secret object is involved at any point.

Two trade-offs against External Secrets Operator: the Vault Agent injector requires every consuming app to declare its Vault contract via pod annotations (more invasive but more explicit), and rendered secrets live only on the pod’s tmpfs (better blast radius, but apps that expect to read from envFrom: secretRef need a different pattern — typically loading from a file or using the agent-inject-default-template). The installer below sets up the injector in HA mode, configures the Kubernetes auth method on Vault for this cluster, defines a sample Vault policy and role for a “billing-api” workload, and ships a sample deployment manifest that demonstrates the annotations.

How to verify

After install, the injector deployment should be Ready and the mutating webhook should be registered:

kubectl -n vault get pods -l app.kubernetes.io/name=vault-agent-injector
# NAME                                    READY   STATUS    AGE
# vault-agent-injector-7f8b5c8c44-abcde   1/1     Running   2m
# vault-agent-injector-7f8b5c8c44-fghij   1/1     Running   2m

kubectl get mutatingwebhookconfiguration vault-agent-injector-cfg \
  -o jsonpath='{.webhooks[*].name}'
# vault.hashicorp.com

Apply the sample deployment in the fix below, then confirm the agent rendered the secret onto the pod’s tmpfs:

kubectl -n billing exec deploy/billing-api -c billing-api \
  -- ls -la /vault/secrets/
# total 12
# -rw-r--r-- 1 root root  42 May 14 12:34 database

kubectl -n billing exec deploy/billing-api -c billing-api \
  -- head /vault/secrets/database
# username=v-kubernetes-billing-api-...
# password=A1B2C3...

Check the agent renewed the lease — annotations include a TTL, and the agent’s log should show periodic renewal:

kubectl -n billing logs deploy/billing-api -c vault-agent | grep -i renew | tail -5

The fix

Save the script as /root/install-vault-injector.sh and run it on a node with kubectl and helm configured for the target cluster. It performs the full installer: prerequisite check (Vault reachable, kubectl works), Helm chart 0.28.x install of the Vault Agent Injector in HA mode (two replicas, pod anti-affinity), configuration of the Vault Kubernetes auth method against this cluster’s API, a sample Vault policy + role for a billing-api workload that reads from kv/billing/* and gets dynamic Postgres creds from database/creds/billing-readwrite, RBAC for the injector’s ServiceAccount, and a sample annotated deployment plus verification.

#!/usr/bin/env bash
set -euo pipefail

### Kubernetes 1.30 — install Vault Agent Injector (HA, annotation-driven)
### Assumes Vault is reachable and you have a Vault token with policy write rights
### exported as VAULT_TOKEN; the script does NOT mint root tokens for you

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT ===
INJECTOR_CHART_VERSION="0.28.1"     # hashicorp/vault chart (injector only)
INJECTOR_APP_VERSION="1.4.2"
INJECTOR_NAMESPACE="vault"
INJECTOR_RELEASE="vault-injector"

VAULT_ADDR="https://vault.internal.example.com:8200"
VAULT_K8S_AUTH_MOUNT="kubernetes-cluster-01"
CLUSTER_API="https://kubernetes.default.svc:443"

SAMPLE_NAMESPACE="billing"
SAMPLE_SA="billing-api"
SAMPLE_VAULT_ROLE="billing-api"
SAMPLE_KV_PATH="kv/billing"
# ============

export VAULT_ADDR VAULT_TOKEN

echo
echo "========================================"
echo "Vault Agent Injector on Kubernetes"
echo "========================================"
echo

echo "==> Prerequisite check"
command -v kubectl >/dev/null || { echo "kubectl missing"; exit 1; }
command -v helm    >/dev/null || { echo "helm missing"; exit 1; }
command -v vault   >/dev/null || { echo "vault CLI missing"; exit 1; }
kubectl cluster-info >/dev/null
vault token lookup >/dev/null || { echo "VAULT_TOKEN invalid or unset"; exit 1; }

echo "==> Add HashiCorp Helm repo"
helm repo add hashicorp https://helm.releases.hashicorp.com
helm repo update

echo "==> Create namespace"
kubectl create ns "${INJECTOR_NAMESPACE}" --dry-run=client -o yaml | kubectl apply -f -

echo "==> Values file (injector only, external Vault)"
cat > /etc/vault-injector-values.yaml <<EOF
global:
  enabled: true
  externalVaultAddr: "${VAULT_ADDR}"

server:
  enabled: false       # external Vault, do not deploy server

injector:
  enabled: true
  replicas: 2
  image:
    repository: hashicorp/vault-k8s
    tag: ${INJECTOR_APP_VERSION}
  agentImage:
    repository: hashicorp/vault
    tag: "1.17.6"

  resources:
    requests: { cpu: 100m, memory: 128Mi }
    limits:   { cpu: 500m, memory: 384Mi }

  certs:
    secretName: null       # chart generates self-signed; rotate via cert-manager later
    caBundle: ""

  failurePolicy: Fail
  reinvocationPolicy: IfNeeded

  affinity: |
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        - labelSelector:
            matchLabels:
              app.kubernetes.io/name: vault-agent-injector
              app.kubernetes.io/instance: ${INJECTOR_RELEASE}
              component: webhook
          topologyKey: kubernetes.io/hostname

  securityContext:
    pod:
      runAsNonRoot: true
      runAsUser: 100
      runAsGroup: 1000
      fsGroup: 1000

  metrics:
    enabled: false       # flip true once Prometheus Operator is installed

  webhook:
    namespaceSelector:
      matchExpressions:
        - key: vault-injection
          operator: NotIn
          values: ["disabled"]
EOF

echo "==> Install injector"
helm upgrade --install "${INJECTOR_RELEASE}" hashicorp/vault \
  --namespace "${INJECTOR_NAMESPACE}" \
  --version "${INJECTOR_CHART_VERSION}" \
  -f /etc/vault-injector-values.yaml \
  --wait --timeout 5m

kubectl -n "${INJECTOR_NAMESPACE}" rollout status \
  deploy/vault-injector-agent-injector --timeout=5m

echo "==> Configure Vault Kubernetes auth method"
if ! vault auth list | grep -q "^${VAULT_K8S_AUTH_MOUNT}/"; then
  vault auth enable -path="${VAULT_K8S_AUTH_MOUNT}" kubernetes
fi

# Extract cluster CA from kube-public/cluster-info to seed Vault
CA_CERT="$(kubectl -n kube-public get cm cluster-info \
  -o jsonpath='{.data.kubeconfig}' \
  | grep certificate-authority-data \
  | awk '{print $2}' | base64 -d)"

# Token for Vault to use against the TokenReview API (long-lived, audience-bound)
kubectl -n "${INJECTOR_NAMESPACE}" apply -f - <<EOF
apiVersion: v1
kind: ServiceAccount
metadata:
  name: vault-auth
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: vault-auth-tokenreview
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
  - kind: ServiceAccount
    name: vault-auth
    namespace: ${INJECTOR_NAMESPACE}
---
apiVersion: v1
kind: Secret
metadata:
  name: vault-auth-token
  namespace: ${INJECTOR_NAMESPACE}
  annotations:
    kubernetes.io/service-account.name: vault-auth
type: kubernetes.io/service-account-token
EOF

# Wait for token to be populated
for i in {1..15}; do
  TR_TOKEN="$(kubectl -n "${INJECTOR_NAMESPACE}" get secret vault-auth-token \
    -o jsonpath='{.data.token}' 2>/dev/null | base64 -d)"
  if [[ -n "${TR_TOKEN:-}" ]]; then break; fi
  sleep 2
done

vault write "auth/${VAULT_K8S_AUTH_MOUNT}/config" \
  kubernetes_host="${CLUSTER_API}" \
  kubernetes_ca_cert="${CA_CERT}" \
  token_reviewer_jwt="${TR_TOKEN}" \
  issuer="https://kubernetes.default.svc.cluster.local"

echo "==> Sample Vault policy + role for ${SAMPLE_VAULT_ROLE}"
vault policy write "${SAMPLE_VAULT_ROLE}" -<<POL
path "${SAMPLE_KV_PATH}/data/*" {
  capabilities = ["read"]
}
path "${SAMPLE_KV_PATH}/metadata/*" {
  capabilities = ["read", "list"]
}
path "database/creds/billing-readwrite" {
  capabilities = ["read"]
}
POL

vault write "auth/${VAULT_K8S_AUTH_MOUNT}/role/${SAMPLE_VAULT_ROLE}" \
  bound_service_account_names="${SAMPLE_SA}" \
  bound_service_account_namespaces="${SAMPLE_NAMESPACE}" \
  policies="${SAMPLE_VAULT_ROLE}" \
  ttl="1h" \
  max_ttl="24h"

echo "==> Sample namespace + ServiceAccount + annotated deployment"
kubectl apply -f - <<EOF
apiVersion: v1
kind: Namespace
metadata:
  name: ${SAMPLE_NAMESPACE}
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: ${SAMPLE_SA}
  namespace: ${SAMPLE_NAMESPACE}
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ${SAMPLE_SA}
  namespace: ${SAMPLE_NAMESPACE}
spec:
  replicas: 2
  selector:
    matchLabels:
      app: ${SAMPLE_SA}
  template:
    metadata:
      labels:
        app: ${SAMPLE_SA}
      annotations:
        vault.hashicorp.com/agent-inject: "true"
        vault.hashicorp.com/agent-init-first: "true"
        vault.hashicorp.com/role: "${SAMPLE_VAULT_ROLE}"
        vault.hashicorp.com/auth-path: "auth/${VAULT_K8S_AUTH_MOUNT}"

        # Static KV secret
        vault.hashicorp.com/agent-inject-secret-stripe: "${SAMPLE_KV_PATH}/data/stripe"
        vault.hashicorp.com/agent-inject-template-stripe: |
          {{- with secret "${SAMPLE_KV_PATH}/data/stripe" -}}
          stripe_key={{ .Data.data.key }}
          {{- end }}

        # Dynamic Postgres credential, 30m TTL, renewed by agent
        vault.hashicorp.com/agent-inject-secret-database: "database/creds/billing-readwrite"
        vault.hashicorp.com/agent-inject-template-database: |
          {{- with secret "database/creds/billing-readwrite" -}}
          username={{ .Data.username }}
          password={{ .Data.password }}
          {{- end }}
        vault.hashicorp.com/agent-inject-perms-database: "0440"

        # Agent runs as non-root
        vault.hashicorp.com/agent-run-as-user: "65534"
        vault.hashicorp.com/agent-run-as-group: "65534"
    spec:
      serviceAccountName: ${SAMPLE_SA}
      automountServiceAccountToken: true
      containers:
        - name: ${SAMPLE_SA}
          image: alpine:3.20
          command:
            - sh
            - -c
            - |
              while true; do
                echo "== /vault/secrets =="
                ls -la /vault/secrets/ 2>/dev/null || true
                echo "-- database --"
                cat /vault/secrets/database 2>/dev/null || true
                sleep 60
              done
EOF

echo "==> Wait for sample pod to be Ready (sidecar must auth to Vault)"
kubectl -n "${SAMPLE_NAMESPACE}" rollout status deploy/${SAMPLE_SA} --timeout=3m || {
  echo "Sample deployment failed — describing for triage"
  kubectl -n "${SAMPLE_NAMESPACE}" describe deploy/${SAMPLE_SA} | tail -40
  exit 1
}

echo "==> Verify secret rendered"
POD="$(kubectl -n ${SAMPLE_NAMESPACE} get pod -l app=${SAMPLE_SA} -o name | head -1)"
kubectl -n ${SAMPLE_NAMESPACE} exec ${POD} -c ${SAMPLE_SA} -- ls -la /vault/secrets/
kubectl -n ${SAMPLE_NAMESPACE} exec ${POD} -c ${SAMPLE_SA} -- head /vault/secrets/database || true

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Injector:"
kubectl -n "${INJECTOR_NAMESPACE}" get pods,svc,mutatingwebhookconfiguration | grep -i vault
echo
echo "Sample deployment:"
kubectl -n "${SAMPLE_NAMESPACE}" get pods,deploy
echo
echo "Vault role bound to:"
echo "  namespace=${SAMPLE_NAMESPACE} serviceaccount=${SAMPLE_SA} role=${SAMPLE_VAULT_ROLE}"
echo
echo "To onboard a new workload:"
echo "  1. Define a Vault policy"
echo "  2. Create a role under auth/${VAULT_K8S_AUTH_MOUNT}/role/<name>"
echo "  3. Annotate the pod with vault.hashicorp.com/agent-inject + role + secret paths"

Make it executable and run:

chmod 700 /root/install-vault-injector.sh
export VAULT_ADDR=https://vault.internal.example.com:8200
export VAULT_TOKEN=hvs.... # an admin-capable token, not root
/root/install-vault-injector.sh

The pattern you keep in your head is short: a workload gets a ServiceAccount, the ServiceAccount is bound to a Vault role, the Vault role enforces a Vault policy, and the pod’s annotations spell out which paths to render and into which files. Rotation is the agent’s problem, not yours — for dynamic database credentials, the agent ticks renewal and re-renders the template before the lease expires. For static KV secrets that change in Vault, set vault.hashicorp.com/agent-inject-template-<name> to use the pkiCert or secret helpers with (parseDuration .LeaseDuration) and have the agent send SIGHUP to your app on render — annotation vault.hashicorp.com/agent-inject-command-<name>: "kill -HUP 1".

We deploy the Vault Agent Injector with cert-manager-issued webhook certs, an HA Vault behind it, and the Kubernetes auth method scoped per-cluster as part of Managed Cloud Ops. If your apps are reading secrets from envFrom: secretRef today and you’d like to move them to short-lived leases without rewriting the app, book a discovery call.