Configuration, secrets, storage and access · 6 MIN READ
Secrets: credentials for pods, and why base64 is not protection
Create Secrets from literals or stringData, deliver them as variables or files, and name the controls that actually keep them confidential: RBAC, encryption at rest, external managers and careful logging.
Passwords, API tokens and TLS keys must not be baked into images or ConfigMaps. A Secret is the Kubernetes object for them, and it looks protected because its values appear as gibberish. That gibberish is base64, which anyone can decode; the real protection comes from who may read the object, how etcd stores it, and what your application does with the value.
kubernetes · A MAP OF THE IDEA
- Create the Secret outside Git
- Grant narrow RBAC
- Mount as file or secretKeyRef
- Encrypt etcd, redact logs
Useful when
- Credentials stay out of images and ConfigMaps.
- Mounted Secrets rotate without rebuilding or restarting.
Watch out
- Base64 hides nothing from anyone with read access.
- Pod creation and exec rights also expose Secrets.
Implementation & operation cost: RBAC reviews, an encryption provider for etcd, and application code that never prints a credential.
Secret types, and base64 as encoding
A Secret is a namespaced object like a ConfigMap, with a type that tells tools which keys to expect: Opaque for arbitrary data, kubernetes.io/tls with tls.crt and tls.key, kubernetes.io/dockerconfigjson for image pull credentials, kubernetes.io/basic-auth, kubernetes.io/ssh-auth and the legacy kubernetes.io/service-account-token. Values under data are base64-encoded so that binary content such as a keystore survives JSON and YAML. That is encoding, not encryption: base64 -d reverses it without any key. kubectl create secret tls and kubectl create secret docker-registry build the typed variants on a real cluster; the GopherForge lab simulates only kubectl create secret generic. Like a ConfigMap, a Secret is limited to 1 MiB.
echo -n 's3cr3t-Pa55' | base64
echo 'czNjcjN0LVBhNTU=' | base64 -dThe first line prints czNjcjN0LVBhNTU=. echo -n matters: without it the newline is encoded too, and a password with a trailing newline is a classic cause of authentication failures. The second line turns the value straight back into s3cr3t-Pa55, as anyone who can read the Secret can.
Writing Secrets declaratively
In a manifest, stringData accepts plain text and the API server encodes it into data on write; when a key appears in both, stringData wins. That makes manifests easy to write and just as easy to leak: a Secret manifest committed to Git is a committed password. Keep real values out of the repository and create Secrets from a pipeline, from an encrypted form such as Sealed Secrets or SOPS that only the cluster or the pipeline can decrypt, or from an external secret manager. kubectl create secret generic --from-literal avoids a file on disk, but the value lands in your shell history; --from-file reads it from a file instead.
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
stringData:
POSTGRES_USER: app
POSTGRES_PASSWORD: s3cr3t-Pa55After kubectl apply, kubectl get secret db-credentials -o yaml shows the values encoded under data, as YXBw and czNjcjN0LVBhNTU=, and no stringData field. On a real cluster, client-side kubectl apply also stores the whole manifest, plain text included, in the kubectl.kubernetes.io/last-applied-configuration annotation; kubectl apply --server-side does not.
Environment variable or mounted file
secretKeyRef works exactly like configMapKeyRef, including CreateContainerConfigError when the Secret or key is missing. Variables are convenient but travel far: child processes inherit them, crash reporters and debug endpoints dump them, and kubectl exec ... env prints them for anyone allowed to exec. A secret volume writes each key as a file on a tmpfs, so the value never touches the node's disk; defaultMode restricts the file permissions, and the kubelet refreshes the files when the Secret is rotated, unless they are mounted with subPath. Prefer files for credentials your code can reread, and variables for images that expect them, such as postgres. Many images also accept a _FILE variant, like POSTGRES_PASSWORD_FILE.
apiVersion: apps/v1
kind: Deployment
metadata:
name: db
spec:
replicas: 1
selector:
matchLabels:
app: db
template:
metadata:
labels:
app: db
spec:
containers:
- name: postgres
image: postgres:16
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: POSTGRES_PASSWORD
volumeMounts:
- name: creds
mountPath: /run/secrets/db
readOnly: true
volumes:
- name: creds
secret:
secretName: db-credentials
defaultMode: 0400POSTGRES_PASSWORD is read from the db-credentials key once, at container start. The same Secret is mounted read-only at /run/secrets/db, one file per key, with mode 0400. kubectl describe pod shows the reference, not the value: <set to the key 'POSTGRES_PASSWORD' in secret 'db-credentials'>.
Who can read a Secret
RBAC decides. get on secrets reads one value, and list or watch return every Secret in the namespace with its data, so treat list as read access to all of them. Less obviously, anyone who can create pods or Deployments in a namespace can mount any Secret there and read it from inside the container, and anyone allowed to create pods/exec can print the environment of running pods. By default the API server writes Secrets to etcd unencrypted, so etcd backups contain them too; an EncryptionConfiguration with a KMS v2 provider encrypts them at rest with a key held outside the cluster. External Secrets Operator or the Secrets Store CSI Driver fetch values from Vault or a cloud secret manager, which then owns rotation and auditing.
Keep secrets out of logs
Most leaks are not attacks; they are log lines. A startup message that prints the whole configuration, an error that wraps a connection string, or a panic that dumps a struct all end up in a log system that far more people can read than the Secret. In Go, url.URL.Redacted replaces the password in a URL, and a small type that implements fmt.Stringer and slog.LogValuer makes the safe output the default wherever the value is printed. Errors leak too: url.Parse quotes its input in the error text, so logging that error logs the password. The lab's gopherforge/api image follows this rule: when it logs its database URL, asterisks replace the password.
// Secret holds a credential and never prints it.
type Secret string
func (Secret) String() string { return "[REDACTED]" }
func (Secret) LogValue() slog.Value { return slog.StringValue("[REDACTED]") }
func logDatabase(logger *slog.Logger, raw string) {
u, err := url.Parse(raw)
if err != nil {
logger.Error("DATABASE_URL is not a valid URL") // err would echo raw
return
}
logger.Info("connecting", "database", u.Redacted())
}A Secret value prints as [REDACTED] through fmt's %s and %v and through slog; code that needs the credential converts it explicitly with string(s). logDatabase logs postgres://app:xxxxx@db:5432/app via Redacted, and on a parse error logs a fixed message instead of err, whose text would contain the whole input.
Try it in the lab terminal
Start postgres:16 without a password and read why it crashes, then create a Secret and decode it yourself to see how little base64 hides. Wire the Secret into the Deployment with kubectl set env, let the rollout replace the crashing pod, and read the variable from inside the container. The last two commands ask the authorizer what the namespace's default ServiceAccount may do with Secrets and with exec, which is the access that matters.
kind create cluster
kubectl create deployment db --image=postgres:16
cluster tick 20s
kubectl get pods
kubectl logs deploy/db
kubectl create secret generic db-credentials --from-literal=POSTGRES_PASSWORD='s3cr3t-Pa55'
kubectl get secret db-credentials -o yaml
kubectl get secret db-credentials -o jsonpath='{.data.POSTGRES_PASSWORD}' | base64 -d
kubectl set env deploy/db --from=secret/db-credentials
kubectl rollout status deploy/db
kubectl logs deploy/db
kubectl exec deploy/db -- printenv POSTGRES_PASSWORD
kubectl auth can-i get secrets --as=system:serviceaccount:default:default
kubectl auth can-i create pods/exec --as=system:serviceaccount:default:defaultdb-<hash>-<id> is in CrashLoopBackOff, and its log says You must specify POSTGRES_PASSWORD to a non-empty value for the superuser. The Secret's YAML shows type Opaque and POSTGRES_PASSWORD: czNjcjN0LVBhNTU=, and the jsonpath and base64 -d pipe prints s3cr3t-Pa55 with no key at all. After set env and the rollout, the log ends with database system is ready to accept connections, and printenv prints the password in clear text: exec access is secret access. The last two checks print no, because the default ServiceAccount may neither get Secrets nor exec into pods.
TAKE THIS WITH YOU
A Secret is a namespaced object whose base64 values anyone with read access can decode. Protect it with narrow RBAC on get, list, watch, pod creation and exec, encryption at rest, values kept out of Git and logs, and file mounts where the application can read them.
Check your understanding
A developer has get on secrets in the production namespace. What keeps the database password in db-credentials from them?
Go to the source
Progress stays in this browser. No account needed.