Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 78 ยท Configuration and Secrets

Secrets

Learn Kubernetes Secrets: the built-in types, why base64 is not encryption, env vars versus volumes, encryption at rest, and how to limit who can read them.

A Secret looks almost exactly like a ConfigMap: a named object with keys and values that Pods can read as environment variables or files. The difference is intent. Secrets are for things you should not leak, such as passwords, API tokens, TLS private keys and registry credentials, and the platform treats them more carefully: they are kept in tmpfs (memory) on the node instead of disk, they are sent only to nodes that run Pods needing them, and you can set tighter access rules for them.

But the most important thing to learn about Secrets is a limit. By default a Secret is not encrypted in the API; its values are only base64-encoded, which is a text format, not protection. This lesson explains what that means, the types of Secret that exist, how to deliver them to Pods, and what you must do on top to make them reasonably safe.

Creating a Secret

The data field holds base64-encoded values. Because encoding by hand is awkward, the stringData field accepts plain text and the API server converts it to data on write (it is write-only; you never read it back).

YAML
apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
  namespace: shop
type: Opaque
stringData:
  username: shop_app
  password: "s3cr3t-Passw0rd"

The command line does the encoding for you. These commands are read-only examples here:

Terminal
kubectl create secret generic db-credentials \
  --from-literal=username=shop_app \
  --from-literal=password='s3cr3t-Passw0rd'

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

Notice the last line: anyone allowed to get the Secret can decode it in one step. Keep real secrets out of manifests you commit to Git; the next lesson, External Secrets, Sealed Secrets and Config Patterns, covers how.

Secret types

The type field tells Kubernetes (and tools) what keys to expect, and validates them:

Type Purpose Required keys
Opaque Arbitrary user data (the default) none
kubernetes.io/basic-auth Username and password password (and optionally username)
kubernetes.io/ssh-auth An SSH private key ssh-privatekey
kubernetes.io/tls A certificate and its private key tls.crt, tls.key
kubernetes.io/dockerconfigjson Registry credentials for pulling images .dockerconfigjson
kubernetes.io/service-account-token A long-lived ServiceAccount token (legacy; see Service Accounts) set by the system
bootstrap.kubernetes.io/token Node bootstrap tokens token-id, token-secret

You will use kubernetes.io/tls for Ingress certificates and kubernetes.io/dockerconfigjson for imagePullSecrets:

Terminal
kubectl create secret tls shop-tls --cert=tls.crt --key=tls.key
kubectl create secret docker-registry regcred \
  --docker-server=registry.example.com \
  --docker-username=ci --docker-password='token-here'

Why base64 is not encryption

Base64 turns bytes into a safe subset of ASCII characters. It exists so binary data (like a certificate) can sit inside YAML and JSON. It has no key and no secret algorithm: anyone can reverse it instantly. If you see cGFzc3dvcmQ= in a manifest, you are looking at the word password, in plain sight.

Encoding is not encryption

Base64 A reversible text format with no key.
Encryption Needs a key; useless without it.
Default Secret Base64 only, stored as-is in etcd.

Protection comes from access control and encryption at rest.

1 / 2
Python Base64 round trip: no key needed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is real base64 from Python's standard library, the same transformation Kubernetes applies. The only stand-in is the surrounding API server, which here is just a dictionary.

Using Secrets in a Pod

You deliver Secrets the same two ways as ConfigMaps. As environment variables:

YAML
apiVersion: v1
kind: Pod
metadata:
  name: shop-api
spec:
  containers:
    - name: api
      image: example/shop-api:2.1
      env:
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db-credentials
              key: password

Or as files from a volume, with restrictive permissions:

YAML
spec:
  containers:
    - name: api
      image: example/shop-api:2.1
      volumeMounts:
        - name: creds
          mountPath: /etc/shop/creds
          readOnly: true
  volumes:
    - name: creds
      secret:
        secretName: db-credentials
        defaultMode: 0400

Which is safer? Files are usually the better choice. Environment variables are easy to leak: they show up in crash dumps, in /proc/<pid>/environ, in debug endpoints that print the environment, and they are inherited by every child process. Files can be given strict permissions and updated while the Pod runs (the kubelet refreshes Secret volumes, like ConfigMap volumes, though environment variables and subPath mounts do not update). The trade-off: many programs only read environment variables, and for those it is acceptable if you accept the risks and keep logging clean.

Making Secrets actually safer

Treat the following as a checklist, because the defaults alone are weak.

  1. Restrict reads with RBAC. Anyone with get, list or watch on Secrets in a namespace can read all of them; list shows values too. Give workloads their own ServiceAccount with no Secret access (see Authentication and RBAC). Also remember that anyone who can create a Pod in the namespace can mount any Secret there.
  2. Encrypt at rest. By default the values are stored in etcd as plain base64. The API server can encrypt Secrets before writing them, configured with an EncryptionConfiguration file:
YAML
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
  - resources:
      - secrets
    providers:
      - aescbc:
          keys:
            - name: key1
              secret: <base64-encoded 32-byte key>
      - identity: {}

The first provider is used to write; the others are used to read. identity means "no encryption" and, listed last, lets old unencrypted data still be read. After enabling it, existing Secrets stay unencrypted until they are rewritten (kubectl get secrets -A -o json | kubectl replace -f -). The strongest option is the kms provider, where the data key is protected by an external key service such as a cloud KMS. Managed clouds usually offer a checkbox for this.

  1. Keep etcd access and backups locked down, since they contain every Secret.
  2. Do not commit them to Git in plain form, and do not put them in images or build arguments.
  3. Prefer short-lived credentials. Tokens that expire, or identities that the cloud issues to a Pod, are better than a password that lives for years (see Service Accounts and Workload Identity).
  4. Rotate. Plan how a new value reaches Pods: mounted files update by themselves, environment variables need a rollout.

Like ConfigMaps, a Secret can be immutable: true, and the size limit is 1 MiB.

A look at an access check

The final stand-in models the question "who can read which Secret?", the real center of Secret safety.

Python Who can read the Secret?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note that alice has only list, yet she reads the value. In the real system the effect is the same: Secret values come back in list responses.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What protection does base64 encoding give a Secret's values?

    Base64 only changes the representation of the bytes. Anyone who can read the object can decode it immediately.
  2. 2. You want the API server to store Secrets encrypted in etcd. What do you configure?

    Encryption at rest is an API server setting that encrypts resources like Secrets before they are written to etcd.
  3. 3. Why are Secret volumes generally preferred over environment variables?

    Files give you control over permissions and are updated by the kubelet. Environment variables are copied once and are easy to leak.
  4. 4. A user has RBAC permission to list Secrets in a namespace but not to get them. Can they see the values?

    Listing Secrets returns their contents, so list and watch must be granted as carefully as get.

Summary

  • A Secret is like a ConfigMap meant for sensitive data, with a type that validates expected keys (Opaque, tls, dockerconfigjson, basic-auth and more).
  • Values are base64-encoded, which is not encryption; protection comes from RBAC, encryption at rest and good habits.
  • Prefer mounted files with restrictive permissions to environment variables when the application allows it.
  • Enable API server encryption (ideally with a KMS provider), restrict get, list and watch, and guard etcd and its backups.
  • Do not commit plain Secrets to Git; use a tool that encrypts or fetches them.

Next: External Secrets, Sealed Secrets and Config Patterns.