Browse topics

Secrets

Version
1.37
Review
Draft

Summary#

A Secret holds small sensitive values such as passwords and keys. Pods consume it as environment variables or mounted files. In data the values are base64 encoded; stringData accepts plain text when writing. Limit who can read Secrets with RBAC.

Syntax#

sh
kubectl create secret generic NAME --from-literal=KEY=VALUE --from-file=FILE
kubectl get secret NAME -o jsonpath='{.data.KEY}' | base64 -d
yaml
env:
  - name: DB_PASSWORD
    valueFrom:
      secretKeyRef:
        name: db
        key: password

Example#

The values are made up for this example.

sh
(
  set -eu
  ns="ref-secrets-$$"
  kubectl create namespace "$ns" >/dev/null
  trap 'kubectl delete namespace "$ns" >/dev/null' EXIT
  kubectl wait -n "$ns" --for=create serviceaccount/default --timeout=60s >/dev/null

  kubectl apply -n "$ns" -f - >/dev/null <<'EOF'
apiVersion: v1
kind: Secret
metadata:
  name: db
type: Opaque
stringData:
  username: app
  password: example-password
---
apiVersion: v1
kind: Pod
metadata:
  name: reader
spec:
  restartPolicy: Never
  containers:
    - name: reader
      image: busybox:1.37
      command: ["sh", "-c", "echo \"user=$DB_USER\"; echo \"password bytes=$(wc -c < /etc/db/password)\""]
      env:
        - name: DB_USER
          valueFrom:
            secretKeyRef:
              name: db
              key: username
      volumeMounts:
        - name: db
          mountPath: /etc/db
          readOnly: true
  volumes:
    - name: db
      secret:
        secretName: db
EOF
  kubectl get -n "$ns" secret db -o jsonpath='type={.type}{"\n"}stored={.data.password}{"\n"}'
  encoded=$(kubectl get -n "$ns" secret db -o jsonpath='{.data.password}')
  echo "decoded=$(printf '%s' "$encoded" | base64 -d)"

  kubectl wait -n "$ns" --for=jsonpath='{.status.phase}'=Succeeded pod/reader --timeout=120s >/dev/null
  kubectl logs -n "$ns" reader
)

Expected output#

Text
type=Opaque
stored=ZXhhbXBsZS1wYXNzd29yZA==
decoded=example-password
user=app
password bytes=16

Common mistakes#

Base64 is an encoding, not encryption. By default Secrets are also stored unencrypted in etcd, and anyone who may create a Pod in the namespace can read them through that Pod. Do not commit Secret manifests; configure encryption at rest and narrow RBAC rules.

Use data for server-side apply. The API folds stringData into data on write, so stringData is unsuitable for tracking field ownership.

Version applicability#

The example targets Kubernetes 1.37. Immutable Secrets, set with immutable: true, are stable since 1.21.

The kubelet rejects Secret references in static Pod manifests. Kubernetes 1.37 removed the PreventStaticPodAPIReferences feature gate that previously allowed an opt-out.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0