Secrets: passwords and keys

Like a ConfigMap, handled with more care.

Beginner20 min · lesson 12 of 21
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (4 files, 1 KB): secrets.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/k8s-fund/secrets.tar.gz && tar -xzf secrets.tar.gz, which creates ~/lab/secrets/. SHA-256: aaaed3c85d6cea618282e7f20e9ed2d32ac694416e036f6a1bcc18bfe9204eba

The ConfigMap in lesson 11 held a colour. Now the app also needs a database password. You could put it in the same ConfigMap, but ConfigMaps are meant to be read freely, by people and by tools. Kubernetes has a separate object for values like this, the Secret.

A Secret works almost exactly like a ConfigMap. The differences are in how the cluster handles it: access to Secrets can be locked down on its own, a mounted Secret is kept off the node's disk, and the cluster can encrypt Secrets where it stores them. What a Secret does not do, by default, is encrypt anything, and more people can read it than you might expect.

Create a Secret without a file

--from-literal puts the value straight into the command, so no file with the password ends up on your disk or in a Git repository by accident. (It does end up in your shell history. Real teams fetch the value from a password manager or let a tool create the Secret.)

ubuntu@secopslog-k8s:~/lab/secrets · Kubernetes 1.37
$ kubectl create secret generic db-login --from-literal=username=app --from-literal=password='lab-only-Pa55'
secret/db-login created
$ kubectl get secret db-login && kubectl describe secret db-login
NAME TYPE DATA AGE db-login Opaque 2 1s Name: db-login Namespace: default Labels: <none> Annotations: <none> Type: Opaque Data ==== password: 13 bytes username: 3 bytes

generic makes a Secret of type Opaque, meaning "any keys you like". describe is careful: it shows only how many bytes each value has, 13 for the password and 3 for the username, never the values themselves.

Use it in a Pod

A Pod reads a Secret the same two ways as a ConfigMap, as a variable or as files:

client.yaml
apiVersion: v1
kind: Pod
metadata:
name: client
spec:
containers:
- name: client
image: busybox:1.38.0
command: ["sh", "-c", "trap 'exit 0' TERM; while true; do sleep 1; done"]
env:
- name: DB_USER # one key as an environment variable
valueFrom:
secretKeyRef:
name: db-login
key: username
volumeMounts:
- name: db # every key as a file in /etc/db
mountPath: /etc/db
readOnly: true
volumes:
- name: db
secret:
secretName: db-login
ubuntu@secopslog-k8s:~/lab/secrets · Kubernetes 1.37
$ kubectl apply -f client.yaml && kubectl wait --for=condition=Ready pod/client --timeout=60s
pod/client created pod/client condition met
$ kubectl exec client -- sh -c 'echo "DB_USER=$DB_USER"; ls -l /etc/db/; cat /etc/db/password; echo'
DB_USER=app total 0 lrwxrwxrwx 1 root root 15 Nov 11 09:36 password -> ..data/password lrwxrwxrwx 1 root root 15 Nov 11 09:36 username -> ..data/username lab-only-Pa55
$ kubectl exec client -- sh -c 'grep /etc/db /proc/mounts'
tmpfs /etc/db tmpfs ro,relatime,size=6039664k,inode64,noswap 0 0

The variable DB_USER holds app, and /etc/db has one file per key, holding the plain value. The files are links through ..data, just like a ConfigMap volume, so a mounted Secret also updates after a change while a variable does not. The last command shows where the files live: a tmpfs, which is memory, mounted read-only. The kubelet keeps Secret volumes in memory so the values are never written to the node's disk.

base64 is not encryption

describe hid the values, but anyone allowed to read the Secret object gets them in full:

ubuntu@secopslog-k8s:~/lab/secrets · Kubernetes 1.37
$ kubectl get secret db-login -o jsonpath='{.data.password}'; echo
bGFiLW9ubHktUGE1NQ==
$ kubectl get secret db-login -o jsonpath='{.data.password}' | base64 -d; echo
lab-only-Pa55

The stored value looks scrambled, but it is only base64, a way to write any bytes as plain letters. base64 -d turns it straight back into the password. No key is needed, and none is involved. Treat a Secret's YAML exactly like the password itself: never commit it to Git and never paste it into a ticket.

Who can read Secrets

So what protects a Secret is the API server deciding who may read it. That decision is made by RBAC (role-based access control), which gets its own course later in the track. Two quick checks with kubectl auth can-i, which asks the API server "would this be allowed?":

ubuntu@secopslog-k8s:~/lab/secrets · Kubernetes 1.37
$ kubectl auth can-i get secrets
yes
$ kubectl auth can-i get secrets --as=system:serviceaccount:default:default
no

You are the cluster admin, so yes. The default service account, the identity every Pod in the namespace gets unless told otherwise, gets no. That is good: an app that is broken into cannot simply list the namespace's Secrets.

Permission to read Secrets is not the whole story, though. This Role lets a user called dev create and read Pods, and nothing more:

pod-maker.yaml
# A user called "dev" may run Pods and read their logs in this namespace. Nothing about Secrets.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-maker
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["create", "get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: dev-pod-maker
subjects:
- kind: User
name: dev
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-maker
apiGroup: rbac.authorization.k8s.io
ubuntu@secopslog-k8s:~/lab/secrets · Kubernetes 1.37
$ kubectl apply -f pod-maker.yaml
role.rbac.authorization.k8s.io/pod-maker created rolebinding.rbac.authorization.k8s.io/dev-pod-maker created
$ kubectl get secret db-login --as=dev
Error from server (Forbidden): secrets "db-login" is forbidden: User "dev" cannot get resource "secrets" in API group "" in the namespace "default"
$ kubectl auth can-i create pods --as=dev
yes

--as=dev lets the admin act as dev to test this. Reading the Secret is Forbidden, as expected. But dev may create Pods, and a Pod can mount any Secret in its namespace. So dev writes one that prints the password:

peek.yaml
# Created by "dev", who cannot read Secrets through the API.
apiVersion: v1
kind: Pod
metadata:
name: peek
spec:
restartPolicy: Never
containers:
- name: peek
image: busybox:1.38.0
command: ["cat", "/s/password"]
volumeMounts:
- name: s
mountPath: /s
volumes:
- name: s
secret:
secretName: db-login

Apply it as dev, then run kubectl get pod peek --as=dev until STATUS shows Completed, which takes a few seconds, and read its log:

ubuntu@secopslog-k8s:~/lab/secrets · Kubernetes 1.37
$ kubectl apply -f peek.yaml --as=dev
pod/peek created
$ kubectl get pod peek --as=dev
NAME READY STATUS RESTARTS AGE peek 0/1 Completed 0 5s
$ kubectl logs peek --as=dev
lab-only-Pa55

The password came back through the Pod's log, read by a user who was refused the Secret a moment earlier. Kubernetes does not check whether the person creating a Pod may read the Secrets it mounts. In practice, anyone who can create Pods (or Deployments, or Jobs) in a namespace can read every Secret in it. Put Secrets that need different readers in different namespaces.

Encryption at rest

The API server stores every object in etcd, the cluster's database. By default Secrets are stored there unencrypted, so a copy of the etcd data or of a backup holds every password. The fix is encryption at rest: the cluster admin gives the API server an encryption configuration, ideally backed by a key management service, and from then on Secrets are encrypted before they reach etcd. It is a setting on the API server, not something you switch on per Secret, so this lab does not change it. Managed clouds often turn it on for you. Check yours.

Hands-on

1. Create a second Secret: kubectl create secret generic api-key --from-literal=token='lab-token-123'.

2. Read it back and decode it: kubectl get secret api-key -o jsonpath='{.data.token}' | base64 -d; echo.

3. Check whether dev may list Secrets: kubectl auth can-i list secrets --as=dev.

4. Clean up with kubectl delete pod client peek, kubectl delete -f pod-maker.yaml and kubectl delete secret db-login api-key, then check with kubectl get secrets.

What you should see: step 1 prints secret/api-key created, and step 2 prints exactly lab-token-123. Step 3 answers no, the same as for get, even though dev read a Secret through the peek Pod. Step 4 deletes two Pods, the Role, the RoleBinding and two Secrets, and kubectl get secrets ends with No resources found in default namespace.

Remember

A Secret is base64, not encryption. It is protected by who may read it and by who may create Pods in its namespace, and encrypting it in etcd is a separate cluster setting you have to check.

Quick check
01A colleague says "the password is safe, it is base64 in the Secret". What is the problem?
Correct — base64 -d returned the password with no key at all.
Incorrect — RBAC helps, but anyone who can create Pods in the namespace can still read it.
Incorrect — The value you read back with jsonpath is the same base64 that is stored.
Incorrect — There is no key. base64 is a way of writing bytes as text.
02A user is refused kubectl get secret db-login but may create Pods in the same namespace. Can they read the password?
Incorrect — It does not check the Pod creator's Secret access. That is how dev got the password.
Incorrect — dev had only create, get, list and watch on Pods, plus Pod logs.
Correct — The peek Pod printed the password to its log, created by dev.
Incorrect — A file mount worked for peek. Both ways expose the value.
03Where does the kubelet keep the files of a mounted Secret on the node?
Incorrect — That is where an emptyDir lives by default. Secret volumes are not written to disk.
Correct — /proc/mounts in the Pod showed tmpfs /etc/db mounted read-only.
Incorrect — Volumes are mounted from outside the container, not stored in its layer.
Incorrect — The kubelet copies the values to the node and refreshes them from time to time.

Related