Secrets

A Secret stores sensitive data like passwords and API keys, kept separate from Pod specs.

A Secret is like a ConfigMap but intended for sensitive values: passwords, tokens, TLS certificates, and keys.

How Secrets differ from ConfigMaps

  • Values are stored base64-encoded (this is encoding, not encryption).
  • Kubernetes can encrypt them at rest in etcd if configured.
  • Access can be locked down with RBAC.
Base64 is not security — anyone who can read the Secret can decode it. Restrict access with RBAC and enable encryption at rest.

Using a Secret

Mount it as environment variables or files, exactly like a ConfigMap. Use stringData to write plain values that Kubernetes encodes for you.

Example

Example · yaml
apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
type: Opaque
stringData:
  username: admin
  password: s3cr3t-p4ss
---
apiVersion: v1
kind: Pod
metadata:
  name: app-with-secret
spec:
  containers:
    - name: app
      image: myapp:1.0
      env:
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db-credentials
              key: password

When to use it

  • A team stores the database password in a Secret so it is never hardcoded in a Dockerfile or committed to a Git repository.
  • A CI pipeline creates an image-pull Secret so Kubernetes can authenticate to a private container registry to pull production images.
  • An SRE rotates an API key by updating the Secret object, and pods automatically pick up the new value on the next restart.

More examples

Create a Secret imperatively

Creates a generic Secret from literal values and retrieves the decoded password to verify it was stored correctly.

Example · bash
kubectl create secret generic db-creds \
  --from-literal=username=admin \
  --from-literal=password='S3cr3tP@ss!'

kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -d

Mount Secret as env vars

Injects a single Secret key as a named environment variable, keeping the raw value out of the pod manifest.

Example · yaml
spec:
  containers:
    - name: app
      image: myapp:1.0
      env:
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db-creds
              key: password

Image-pull Secret for private registry

Creates a docker-registry Secret that Kubernetes uses to authenticate when pulling images from a private registry.

Example · bash
kubectl create secret docker-registry regcred \
  --docker-server=registry.example.com \
  --docker-username=ci-bot \
  --docker-password='$CI_TOKEN'

# Reference in pod spec:
# imagePullSecrets:
#   - name: regcred

Discussion

  • Be the first to comment on this lesson.