Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 3

Lab: sync a secret from a manager into Kubernetes

On a local kind cluster, run HashiCorp Vault in dev mode, give External Secrets Operator a least-privilege Vault role through Kubernetes auth, sync a database credential into a Kubernetes Secret with the external-secrets.io/v1 API, then watch it heal and rotate.

Contentsand lesson path

What you will learn

  • Store secrets in a manager (Vault or a cloud secret manager) and deliver them to applications and Kubernetes through External Secrets or SOPS-encrypted files under least-privilege access.

01. The GitOps Conundrum: External Secrets Operator Architecture

GitOps tools such as Argo CD and Flux apply whatever is in a Git repository to the cluster. That works well for Deployments and Services, but a database password must not be committed in plain text, and a plain Kubernetes Secret manifest is only base64-encoded. Yet the application Pods still need a native Secret to read.

The External Secrets Operator (ESO) resolves this. It is a Kubernetes controller that reads values from an external secret manager (HashiCorp Vault, AWS Secrets Manager, Google Secret Manager, Azure Key Vault and others) and writes them into ordinary Kubernetes Secrets. You commit two kinds of custom resource to Git:

  • SecretStore (or the cluster-wide ClusterSecretStore): how to reach the manager and how to authenticate, for example the Vault address, the KV mount and the Vault role.
  • ExternalSecret: what to fetch and where to put it: the remote key and property, and the name of the Kubernetes Secret to create (target.name: db-secret).

Git holds only these references, never the values. The ESO controller fetches the values with its own scoped credentials and re-reads them every refreshInterval, so a rotation in the manager reaches the cluster without a new commit.

Keep two limits in mind. First, the synced Secret is still a normal Kubernetes Secret: it is stored in etcd, and it is only encrypted there if the cluster has encryption at rest configured (see the previous lesson), so RBAC on Secrets still matters. Second, ESO is one of three common patterns:

  • SOPS-encrypted files: values are encrypted in the YAML with age or a cloud KMS key and committed; the GitOps tool decrypts them at apply time. Simple, but you manage the keys, and every rotation is a commit.
  • Sealed Secrets: you encrypt with a public key of a controller in one cluster; only that cluster can decrypt.
  • External Secrets Operator: the manager stays the single source of truth, which suits several clusters and automatic rotation, at the cost of running and securing the operator.

What you need for this lab: Docker, kind v0.33 or later, kubectl, and Helm 3 or 4, with about 4 GB of free memory. The lab was written for External Secrets Operator chart 2.14.0 and the HashiCorp Vault chart 0.34.1 (Vault 2.0.4). Vault runs in dev mode: in memory, unsealed, with the root token root and plain HTTP. That is fine on a throwaway local cluster and never acceptable anywhere else.

02. Step 1: Create a Cluster and Install ESO and Vault

Create a kind cluster, then install both Helm charts at the pinned versions. ESO goes into its own namespace with its CRDs; Vault goes into the vault namespace in dev mode, with the agent injector turned off because ESO does the delivery. The Vault chart also binds its ServiceAccount to the system:auth-delegator role, which Vault needs to check Kubernetes tokens. The last command confirms that the ESO resources are served as v1.

Bash · kind cluster, External Secrets Operator and Vault in dev mode
kind create cluster --name eso-lab
helm repo add external-secrets https://charts.external-secrets.io
helm repo add hashicorp https://helm.releases.hashicorp.com
helm repo update
helm install external-secrets external-secrets/external-secrets \
  --namespace external-secrets --create-namespace --version 2.14.0 --wait
helm install vault hashicorp/vault \
  --namespace vault --create-namespace --version 0.34.1 \
  --set server.dev.enabled=true --set injector.enabled=false
kubectl -n vault wait --for=condition=Ready pod/vault-0 --timeout=180s
kubectl api-resources --api-group=external-secrets.io \
  | grep -E '^(externalsecrets|secretstores) '
Illustrative output · last command only; column spacing may differ
externalsecrets   es   external-secrets.io/v1   true   ExternalSecret
secretstores      ss   external-secrets.io/v1   true   SecretStore

03. Step 2: Store the Secret and Create a Least-Privilege Vault Role

Dev mode already mounts a KV version 2 engine at secret/. Write the lab credential there, then set up Vault's Kubernetes auth method. When ESO logs in, it requests a short-lived token for the eso-service-account ServiceAccount with the audience vault and sends it to /v1/auth/kubernetes/login. Vault checks the token with the Kubernetes TokenReview API, matches the ServiceAccount name, namespace and audience against the role eso-sync-role, and returns a Vault token valid for 15 minutes that carries the eso-read-db policy plus Vault's built-in default policy (which lets a token manage itself, for example look itself up, renew or revoke itself and use its own cubbyhole, but grants no access to secrets; add token_no_default_policy=true to the role to drop it).

The policy allows reading exactly one path. With KV version 2 the API path includes data/, so the policy names secret/data/production/database, while the CLI and ESO address the secret as production/database in the secret mount. The audience setting is optional: current Vault versions log a warning for a role without one but still accept it. Set it anyway, because it stops a ServiceAccount token issued for some other service from being replayed to Vault; that is why the role sets audience=vault and the SecretStore requests tokens for that audience.

The helper function runs the Vault CLI inside the Vault Pod with the dev root token. The values are throwaway lab values.

Bash · KV secret, Kubernetes auth, policy and role
vault_exec() { kubectl -n vault exec -i vault-0 -- env VAULT_TOKEN=root vault "$@"; }

vault_exec kv put secret/production/database \
  username=pg_app_user password=lab-only-value-1
vault_exec auth enable kubernetes
vault_exec write auth/kubernetes/config \
  kubernetes_host=https://kubernetes.default.svc
vault_exec policy write eso-read-db - <<'EOF'
path "secret/data/production/database" {
  capabilities = ["read"]
}
EOF
vault_exec write auth/kubernetes/role/eso-sync-role \
  bound_service_account_names=eso-service-account \
  bound_service_account_namespaces=default \
  audience=vault token_policies=eso-read-db token_ttl=15m
Illustrative output · the kv put metadata table is omitted
Success! Enabled kubernetes auth method at: kubernetes/
Success! Data written to: auth/kubernetes/config
Success! Uploaded policy: eso-read-db
Success! Data written to: auth/kubernetes/role/eso-sync-role

04. Step 3: Apply the SecretStore and ExternalSecret

Save the three manifests below under k8s/secrets/. The ServiceAccount is the identity Vault trusts; it needs no permissions inside Kubernetes. The SecretStore points ESO at the in-cluster Vault Service and names the role and the token audience. Because a SecretStore is namespaced, only ExternalSecret objects in default can use it; a ClusterSecretStore would need namespace conditions to keep other teams out.

The ExternalSecret maps two properties of the Vault secret to two keys of the Kubernetes Secret db-secret. creationPolicy: Owner makes ESO the owner of that Secret, so ESO recreates it if it disappears and deletes it with the ExternalSecret. The refreshInterval of one minute keeps the lab quick; one hour is a common production value. spec.target.template (not used here) can also build values such as a full connection string from several properties.

In production, the server URL must use https:// with the Vault CA supplied through caProvider or caBundle. If Vault is unreachable later, ESO keeps the existing Secret and reports SecretSyncedError, so applications keep running while you get an alert.

YAML · k8s/secrets/service-account.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: eso-service-account
  namespace: default
YAML · k8s/secrets/vault-backend.yaml
apiVersion: external-secrets.io/v1
kind: SecretStore
metadata:
  name: vault-backend
  namespace: default
spec:
  provider:
    vault:
      # Lab only: the Vault dev server speaks plain HTTP.
      # In production use https:// plus caProvider or caBundle.
      server: "http://vault.vault.svc:8200"
      path: "secret"
      version: "v2"
      auth:
        kubernetes:
          mountPath: "kubernetes"
          role: "eso-sync-role"
          serviceAccountRef:
            name: eso-service-account
            audiences:
              - vault
YAML · k8s/secrets/database-credentials.yaml
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
  name: db-secret
  namespace: default
spec:
  refreshInterval: "1m" # short for the lab; 1h is a common default
  secretStoreRef:
    name: vault-backend
    kind: SecretStore
  target:
    name: db-secret # the Kubernetes Secret ESO creates and owns
    creationPolicy: Owner
  data:
    - secretKey: DB_USERNAME
      remoteRef:
        key: production/database # read as secret/data/production/database
        property: username
    - secretKey: DB_PASSWORD
      remoteRef:
        key: production/database
        property: password

Before applying, check that no manifest in the folder still uses the old API. This is worth keeping as a CI step in a GitOps repository, because a current ESO install rejects such files.

Bash · find manifests that still use v1beta1
grep -rn 'external-secrets.io/v1beta1' k8s/ || echo 'OK: no v1beta1 manifests'
Expected output
OK: no v1beta1 manifests
Bash · apply and check the status of both resources
kubectl apply -f k8s/secrets/
kubectl get secretstore vault-backend
kubectl wait externalsecret/db-secret --for=condition=Ready --timeout=60s
kubectl get externalsecret db-secret
Illustrative output · ages and spacing will differ
externalsecret.external-secrets.io/db-secret created
serviceaccount/eso-service-account created
secretstore.external-secrets.io/vault-backend created
NAME            AGE   STATUS   CAPABILITIES   READY
vault-backend   5s    Valid    ReadWrite      True
externalsecret.external-secrets.io/db-secret condition met
NAME        STORETYPE    STORE          REFRESH INTERVAL  STATUS        READY  LAST SYNC
db-secret   SecretStore  vault-backend  1m                SecretSynced  True   8s

05. Step 4: Verify, Break It, and Rotate

First confirm that the Secret exists with the expected keys and decode the username. Then try three things that show how the operator behaves:

  1. Self-healing: delete db-secret. ESO watches the Secrets it owns, so it usually recreates it within seconds; at the latest it does so on the next refresh.
  2. Rotation: change the password in Vault and ask ESO to sync now with the force-sync annotation instead of waiting for the refresh interval. The Secret changes, but Pods that read it as environment variables keep the old value until they restart, which is why teams pair ESO with a rollout trigger such as Stakater Reloader.
  3. Least privilege (negative test): ask for a path the policy does not allow. The sync must fail with a permission error, and no Secret may be created.
Bash · inspect, delete, rotate
kubectl get secret db-secret -o jsonpath='{.data.DB_USERNAME}' | base64 -d; echo

# 1. Self-healing
kubectl delete secret db-secret
sleep 10; kubectl get secret db-secret

# 2. Rotation
vault_exec kv patch secret/production/database password=lab-only-value-2
kubectl annotate externalsecret db-secret force-sync="$(date +%s)" --overwrite
sleep 10
kubectl get secret db-secret -o jsonpath='{.data.DB_PASSWORD}' | base64 -d; echo
Illustrative output · ages will differ
pg_app_user
secret "db-secret" deleted
NAME        TYPE     DATA   AGE
db-secret   Opaque   2      9s
externalsecret.external-secrets.io/db-secret annotated
lab-only-value-2
Bash · negative test: a path outside the policy must be refused
vault_exec kv put secret/production/payments api_key=lab-only-not-allowed
kubectl apply -f - <<'EOF'
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
  name: payments-secret
  namespace: default
spec:
  refreshInterval: "1m"
  secretStoreRef: {name: vault-backend, kind: SecretStore}
  target: {name: payments-secret}
  data:
    - secretKey: API_KEY
      remoteRef: {key: production/payments, property: api_key}
EOF
sleep 10; kubectl get externalsecret payments-secret
kubectl get secret payments-secret
Illustrative output · the sync is refused and no Secret exists (LAST SYNC column omitted)
externalsecret.external-secrets.io/payments-secret created
NAME             STORETYPE    STORE          REFRESH INTERVAL  STATUS             READY
payments-secret  SecretStore  vault-backend  1m                SecretSyncedError  False
Error from server (NotFound): secrets "payments-secret" not found

06. Check your understanding

Practice check · 3 questions

External Secrets API versions, Vault policies and rotation

Three questions on failures you may meet in the External Secrets lab.

Q1. After upgrading External Secrets Operator to a current release, applying an old manifest fails with `no matches for kind "ExternalSecret" in version "external-secrets.io/v1beta1"`. What is the right fix?
Q2. Using the `vault-backend` store from this lab, a team adds an ExternalSecret for `production/payments`. It shows `SecretSyncedError`, and `kubectl describe` reports `permission denied` from Vault. What is the most likely cause?
Q3. A security administrator updates a database password inside HashiCorp Vault. The application reads `DB_PASSWORD` from an environment variable. What happens next with this lab's setup?
Practice only: not graded, not saved, not evidence.

07. Apply it

Move one real credential of your own project out of Git:

  • Store it in the manager: put the database password in Vault (or your cloud secret manager) and delete it from every manifest and .env file in the repository.
  • One identity and one policy per workload: give each application namespace its own ServiceAccount, Vault role and policy that names only its paths, and keep SecretStore objects namespaced rather than sharing one ClusterSecretStore.
  • Commit only references: add the ExternalSecret next to the Deployment that uses it, with external-secrets.io/v1.
  • Plan for rotation: choose a refreshInterval that matches how fast a rotated value must arrive, and add a rollout trigger (for example Stakater Reloader) for Pods that read environment variables.
  • Alert on failures: alert when an ExternalSecret is not Ready (ESO exposes this as a Prometheus metric), so an expired Vault role is noticed before the old credential is revoked.
  • If your team uses SOPS instead: encrypt only the data and stringData fields with an age key, keep the private key out of the repository, and document who can decrypt.

08. Review prompt

Without looking back, explain how External Secrets Operator lets you keep secrets out of Git while Pods still receive native Secrets. Describe what the SecretStore and the ExternalSecret each declare, walk through how ESO logs in to Vault with a ServiceAccount token (including the audience), and say what happens when Vault is unreachable, when the Secret is deleted and when the password is rotated. Why is the synced Secret still sensitive inside the cluster?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check