Lesson 51 · Section 5: Application Lifecycle Management
Lesson 51: Secrets: passwords, keys and tokens for your Pods
What a Secret is and what it is not, why base64 is not encryption, how to create Secrets quickly, how Pods receive them as environment variables or files, and who can really read them. · 22 min read · 4 min video
Official competency this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why Secrets exist
Almost every application needs data that must not be public: a database password, an API key, a TLS private key, the login for a private image registry. That data has to live somewhere, and the obvious places are all bad:
- In the image. Everyone who can pull the image, and every layer cache and registry along the way, has the password. Changing it means building a new image.
- In the Pod manifest. The manifest goes to Git, shows up in
kubectl describe podandkubectl get pod -o yaml, and is readable by anyone who may look at Pods. - In a ConfigMap. ConfigMaps are designed to be read widely. Nothing treats their content with care.
A Secret is a separate API object for exactly this data. Because it is its own object, the cluster can give it its own access rules, its own storage encryption and more careful handling on the node, and you can change a password without touching the image or the Deployment.
What a Secret is
A Secret is a namespaced object (kind: Secret, API version v1) that holds a map of keys to small values. It looks
almost exactly like a ConfigMap:
apiVersion: v1
kind: Secret
metadata:
name: db-creds
namespace: shop
type: Opaque
data:
username: c2hvcA== # "shop"
password: czNjcjN0LXB3 # "s3cr3t-pw"
Four things are worth knowing about its fields:
dataholds values in base64. The encoding exists so that a value can be any bytes at all (a binary key, a certificate), not to hide anything.stringDatalets you write values as plain text. The API server encodes them and merges them intodatawhen it stores the object. It is write-only: you never seestringDatawhen you read a Secret back. If a key is in both,stringDatawins.typetells Kubernetes and its tools what the Secret is for. For most types the API server checks that the expected keys are present.immutable: truefreezes the content. See "Using it" below.
One Secret can hold at most 1 MiB of data, and a Pod can only use Secrets from its own namespace.
| Type | Used for | Keys it must have |
|---|---|---|
Opaque | Anything you like. The default when you name no type | None |
kubernetes.io/tls | A certificate and its private key, for example for an Ingress | tls.crt, tls.key |
kubernetes.io/dockerconfigjson | Login for a private image registry | .dockerconfigjson |
kubernetes.io/basic-auth | A username and password | username or password |
kubernetes.io/ssh-auth | An SSH private key | ssh-privatekey |
kubernetes.io/service-account-token | A long-lived ServiceAccount token (legacy) | Filled in by the control plane |
bootstrap.kubernetes.io/token | A token that lets a new node join (kubeadm join) | token-id, token-secret |
How a Pod receives a Secret
Parts:
- Env variables (DB_PASSWORD=...), in Container in the Pod
- Secret db-creds (username, password)
- Files (/etc/db/password), in Container in the Pod
Connections:
- Secret db-creds to Env variables: secretKeyRef
- Secret db-creds to Files: volume
A Secret has no effect until a Pod refers to it. There are two ways to get its values into a container, and a third use that never reaches the container at all.
| As environment variables | As files in a volume | |
|---|---|---|
| How | env[].valueFrom.secretKeyRef for one key, envFrom[].secretRef for all keys | volumes[].secret plus a volumeMount |
| What the app sees | A variable such as DB_PASSWORD | One file per key, for example /etc/db/password |
| When the Secret changes | Nothing, until the container restarts | Files are refreshed by the kubelet, usually within a minute |
| Good for | Apps that read their settings from the environment | Certificates, key files, apps that reload files |
| Risk | Variables leak easily: crash dumps, debug pages, child processes, env in a shell | Files can be given tight permissions |
The third use is imagePullSecrets. The kubelet uses a registry Secret to pull the Pod's image from a private
registry. The container itself never sees it.
In all three cases the value arrives decoded. The application reads s3cr3t-pw, not base64.
How it works underneath
Parts:
- kubectl (create secret)
- API server (checks RBAC)
- etcd (base64, not encrypted)
- kubelet (on the Pod's node)
- tmpfs volume (in RAM, not on disk)
- Container (reads files)
Connections:
- kubectl to API server: HTTPS
- API server to etcd: stores
- API server to kubelet: only its Pods' Secrets
- kubelet to tmpfs volume: writes the keys
- tmpfs volume to Container: mounts
- You send the Secret to the API server, over HTTPS. The API server checks that you may create Secrets in that namespace and validates the type.
- The API server stores it in etcd. Without further setup the stored value is the same base64 you sent. Anyone who can read etcd's files, or an etcd backup, can read every Secret in the cluster. Switching on encryption at rest fixes that, and it is the subject of the next lesson.
- A Pod that uses the Secret is scheduled to a node. That node's kubelet asks the API server for the Secret. The API server's Node authorizer only lets a kubelet read Secrets that are referenced by Pods bound to its own node, so a compromised node cannot collect the whole cluster's Secrets.
- The kubelet delivers it. For environment variables it passes the decoded values to the container runtime when the container is created. For a volume it writes one file per key into a tmpfs, a file system that lives in RAM, and mounts that into the container read-only. The Secret is never written to the node's disk.
- When the Pod goes away, the kubelet removes its copy of the Secret.
Under the hood · How a mounted Secret updates without a restart
The kubelet keeps watching the Secrets its Pods use. When one changes, it writes the new files into a fresh
timestamped directory inside the volume and then switches a symbolic link called ..data to point at it. The file you
see, such as /etc/db/password, is itself a link through ..data, so all keys change at the same instant and the
application never sees a half-updated set.
Two consequences follow. First, the update is not immediate: it can take up to the kubelet's sync period plus its
cache delay, in practice well under two minutes. Second, a container that mounts a single key with subPath gets
a plain copy of the file instead of the link, so it never receives updates.
Kubernetes also does not tell the application anything. An app that read the file once at startup keeps the old value until it reads the file again or restarts.
Under the hood · ServiceAccount tokens are no longer Secrets
In older clusters every ServiceAccount got a Secret of type kubernetes.io/service-account-token with a token that
never expired, and Pods mounted it. Since Kubernetes 1.24 that Secret is no longer created. The kubelet now requests
a short-lived token for each Pod through the TokenRequest API and mounts it with a projected volume at
/var/run/secrets/kubernetes.io/serviceaccount.
So kubectl get secrets in a fresh namespace shows nothing, and that is correct. If you need a token by hand, use
kubectl create token <serviceaccount>. You can still create a token Secret explicitly, by setting the type and the
annotation kubernetes.io/service-account.name, but treat it as a last resort.
Who can really read it
Parts:
- Pod creator (same namespace)
- User with get (RBAC on secrets)
- Secret (base64 values)
- etcd access (files or backups)
- root on the node (sees Pod volumes)
Connections:
- User with get to Secret: get
- Pod creator to Secret: mounts it in a Pod
- etcd access to Secret: reads
- root on the node to Secret: reads the tmpfs
"Secret" describes the intent, not a guarantee. There are four ways to the value, and you have to close each one:
| Path | What closes it |
|---|---|
get, list or watch on Secrets through the API | Narrow RBAC. list and watch return the full values too, not only names |
| Creating a Pod in the namespace that mounts the Secret | Limit who may create Pods (and Deployments, Jobs, CronJobs) there. Use separate namespaces for separate trust levels |
| Reading etcd's data directory or a backup | Encryption at rest, and tight access to control plane nodes and backup files |
| Root on a node, which can look into the tmpfs of local Pods | Node hardening. The Node authorizer limits the damage to Secrets of Pods on that node |
Larger setups often keep the real values outside the cluster, in a vault or a cloud secret manager, and sync or mount them with tools such as the Secrets Store CSI driver. That is beyond the CKA; the exam expects you to create, use and inspect ordinary Secrets.
Using it
Example · Create Secrets imperatively
kubectl create secret has three subcommands. All of them take plain values and do the encoding.
# generic = type Opaque. From literal values:
kubectl -n shop create secret generic db-creds \
--from-literal=username=shop --from-literal=password='s3cr3t-pw'
# From files: the key is the file name, unless you give one
kubectl -n shop create secret generic ssh-key --from-file=id_ed25519
kubectl -n shop create secret generic ssh-key --from-file=private=./id_ed25519
# From a KEY=value file, one key per line
kubectl -n shop create secret generic app-env --from-env-file=app.env
# TLS: checks that the certificate and the key belong together
kubectl -n shop create secret tls web-tls --cert=tls.crt --key=tls.key
# Login for a private registry
kubectl -n shop create secret docker-registry regcred \
--docker-server=registry.example.com --docker-username=ci --docker-password='pw'
Put values with special characters such as $, ! or & in single quotes, or the shell changes them before
kubectl ever sees them.
Example · Write a Secret as a manifest
When the task asks for a file, generate it rather than typing base64:
kubectl -n shop create secret generic db-creds \
--from-literal=username=shop --from-literal=password='s3cr3t-pw' \
--dry-run=client -o yaml > db-creds.yaml
If you do write one by hand, stringData saves you the encoding step:
apiVersion: v1
kind: Secret
metadata:
name: db-creds
namespace: shop
type: Opaque
stringData:
username: shop
password: s3cr3t-pw
After kubectl apply -f, reading it back shows only data with base64 values.
Example · Inspect and decode a Secret
kubectl -n shop get secrets # NAME, TYPE, DATA (number of keys), AGE
kubectl -n shop describe secret db-creds # keys and sizes in bytes, never the values
kubectl -n shop get secret db-creds -o yaml # the base64 values
# One key, decoded
kubectl -n shop get secret db-creds -o jsonpath='{.data.password}' | base64 -d
# A key with a dot in its name needs a backslash
kubectl -n shop get secret web-tls -o jsonpath='{.data.tls\.crt}' | base64 -d
The size in describe is a quick check: a 9 character password that shows as 10 bytes has a stray newline in it.
Example · Use a Secret as environment variables
One key into one variable, and then every key at once:
apiVersion: v1
kind: Pod
metadata:
name: api
namespace: shop
spec:
containers:
- name: api
image: shop/api:2.4
env:
- name: DB_PASSWORD # the variable's name in the container
valueFrom:
secretKeyRef:
name: db-creds # the Secret
key: password # the key inside it
envFrom:
- secretRef:
name: db-creds # creates the variables "username" and "password"
prefix: DB_ # optional: makes them DB_username and DB_password
For an existing Deployment there is a shortcut that writes the secretKeyRef entries for you:
kubectl -n shop set env deployment/api --from=secret/db-creds --prefix=DB_
kubectl -n shop exec deploy/api -- env | grep DB_
Example · Mount a Secret as files
apiVersion: v1
kind: Pod
metadata:
name: api
namespace: shop
spec:
containers:
- name: api
image: shop/api:2.4
volumeMounts:
- name: db
mountPath: /etc/db
readOnly: true
volumes:
- name: db
secret:
secretName: db-creds # note: secretName, not name
defaultMode: 0400 # owner may read, nobody else
items: # optional: pick keys and choose file names
- key: password
path: db-password
Without items, every key becomes a file named after the key: /etc/db/username and /etc/db/password. With items,
only the listed keys appear, here as /etc/db/db-password. The default file mode is 0644.
kubectl -n shop exec api -- ls -l /etc/db
kubectl -n shop exec api -- cat /etc/db/db-password # prints s3cr3t-pw, already decoded
Mounting a volume at a path hides whatever the image had in that directory. Mount Secrets into a directory of their own.
Example · Pull an image from a private registry
spec:
imagePullSecrets:
- name: regcred # a docker-registry Secret in the same namespace
containers:
- name: api
image: registry.example.com/shop/api:2.4
To avoid repeating this in every Pod, attach the Secret to the namespace's ServiceAccount instead. Every Pod that uses that ServiceAccount then gets it automatically:
kubectl -n shop patch serviceaccount default \
-p '{"imagePullSecrets":[{"name":"regcred"}]}'
Example · Change a Secret, and freeze one
kubectl -n shop edit secret db-creds # values here are base64: encode the new one first
# Easier: regenerate the manifest and apply it over the old one
kubectl -n shop create secret generic db-creds \
--from-literal=username=shop --from-literal=password='n3w-pw' \
--dry-run=client -o yaml | kubectl apply -f -
kubectl -n shop rollout restart deployment/api # needed for env variables, harmless for volumes
A Secret with immutable: true cannot be changed at all, neither its data nor the immutable field itself. The only
way forward is to delete it, create it again and restart the Pods that use it. In return, nobody can break running
applications with a bad edit, and the kubelets stop watching it, which lightens the load on the API server in clusters
with many Secrets.
Tricks
Common mistakes
- Treating base64 as protection. It is a reversible encoding. A Secret manifest in Git is a leaked password.
- Putting plain text under
data. The API server rejects values that are not valid base64, or worse, accepts a value that happens to be valid and decodes it to garbage. Plain text goes understringData. - Encoding twice.
--from-literalandstringDataalready encode. Passing them a base64 string gives the application base64 instead of the password. - Expecting environment variables to follow a change. They are fixed when the container starts. Run
kubectl rollout restartafter changing the Secret. - Using
subPathand expecting updates. AsubPathmount never refreshes. - Referring to a Secret in another namespace. There is no way to do that. Copy the Secret into the Pod's namespace.
- Writing
namewheresecretNamebelongs. A volume usessecret.secretName. The API server rejects the unknown field, andkubectl explainsettles it in seconds. - Printing Secrets while debugging.
kubectl exec ... -- env,set -xin scripts and application start-up logs all put the value where many more people can read it. - Handing out
liston Secrets. Alistreturns every value in the namespace, exactly likegeton each one.
Recap
- A Secret holds small private values (at most 1 MiB) as base64, which is encoding and not encryption.
- Create it with
kubectl create secret generic | tls | docker-registry; decode a key with-o jsonpath='{.data.KEY}' | base64 -d. - Pods use it as environment variables (
secretKeyRef,envFrom.secretRef), as files (volumes.secret.secretName) or for image pulls (imagePullSecrets), and only from their own namespace. - Mounted files follow changes within about a minute; environment variables and
subPathmounts need a restart. - The kubelet only receives the Secrets of its own Pods and keeps them in memory.
- Real protection is RBAC, control over who may create Pods, and encryption at rest, which the next lesson covers.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.
Move a database password from a Deployment into a Secret, and deliver an API key as a file only its owner can read.
Fix · Level 2 · standard · target 15 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.