Secrets
A Secret is like a ConfigMap for sensitive data: passwords, API tokens, TLS keys, registry credentials. It is consumed the same ways (env vars or mounted files), but Kubernetes treats it more carefully: it is only sent to nodes that run a Pod using it, kept in memory (tmpfs) on those nodes, and RBAC usually restricts who can read Secrets.
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
stringData: # plain text in, stored base64-encoded
username: shop
password: s3cr3t-Pa55kubectl create secret generic db-credentials --from-literal=username=shop --from-literal=password='s3cr3t-Pa55'
kubectl get secret db-credentials -o jsonpath='{.data.password}' | base64 -dBase64 is not encryption
In data, values are base64-encoded, which only makes binary data safe to put in YAML. Anyone who can read the object can decode it:
import base64
secret = {
"data": {
"username": base64.b64encode(b"shop").decode(),
"password": base64.b64encode(b"s3cr3t-Pa55").decode(),
}
}
print("stored in the API:", secret["data"])
for key, value in secret["data"].items():
print(f"decoded {key}: {base64.b64decode(value).decode()}")stored in the API: {'username': 'c2hvcA==', 'password': 'czNjcjN0LVBhNTU='}
decoded username: shop
decoded password: s3cr3t-Pa55
So protect Secrets properly:
| Measure | Why |
|---|---|
Encryption at rest (EncryptionConfiguration, or a KMS provider) |
etcd backups and disks don't contain plain values. Managed clusters often enable this by default. |
RBAC: few people/apps may get/list Secrets |
Reading a Secret = knowing the password. Note that anyone who can create Pods in a namespace can mount its Secrets. |
| Don't commit Secrets to Git | Use Sealed Secrets, SOPS, or the External Secrets Operator to sync from Vault / AWS Secrets Manager / GCP Secret Manager |
| Prefer files over env vars | Env vars leak into crash dumps, ps e, child processes and logs more easily |
Secret types
type |
Required keys | Used by |
|---|---|---|
Opaque |
anything | Your apps |
kubernetes.io/tls |
tls.crt, tls.key |
Ingress/Gateway TLS |
kubernetes.io/dockerconfigjson |
.dockerconfigjson |
imagePullSecrets for private registries |
kubernetes.io/basic-auth |
username, password |
Some controllers |
kubernetes.io/service-account-token |
(filled in automatically) | Legacy long-lived tokens |
The API server checks the required keys for typed Secrets. A model of that validation:
REQUIRED = {
"Opaque": [],
"kubernetes.io/tls": ["tls.crt", "tls.key"],
"kubernetes.io/dockerconfigjson": [".dockerconfigjson"],
"kubernetes.io/basic-auth": [],
}
def validate(secret):
t = secret.get("type", "Opaque")
keys = set(secret.get("data", {})) | set(secret.get("stringData", {}))
missing = [k for k in REQUIRED[t] if k not in keys]
if t == "kubernetes.io/basic-auth" and not keys & {"username", "password"}:
missing.append("username or password")
return "valid" if not missing else f"invalid: missing {', '.join(missing)}"
examples = {
"app-secret": {"stringData": {"API_TOKEN": "abc"}},
"shop-tls": {"type": "kubernetes.io/tls", "data": {"tls.crt": "LS0t", "tls.key": "LS0t"}},
"half-tls": {"type": "kubernetes.io/tls", "data": {"tls.crt": "LS0t"}},
"registry": {"type": "kubernetes.io/dockerconfigjson", "data": {"config.json": "e30="}},
}
for name, s in examples.items():
print(f"{name:11} {s.get('type', 'Opaque'):31} {validate(s)}")app-secret Opaque valid
shop-tls kubernetes.io/tls valid
half-tls kubernetes.io/tls invalid: missing tls.key
registry kubernetes.io/dockerconfigjson invalid: missing .dockerconfigjson
Using a Secret
spec:
imagePullSecrets:
- name: registry-credentials # pull from a private registry
containers:
- name: api
image: registry.example.com/shop/api:2.3.1
env:
- name: DB_USER
valueFrom:
secretKeyRef: {name: db-credentials, key: username}
volumeMounts:
- name: db
mountPath: /run/secrets/db
readOnly: true
volumes:
- name: db
secret:
secretName: db-credentials
defaultMode: 0400 # owner-read onlyThe app then reads /run/secrets/db/password. Here is a typical reading helper that prefers a mounted file and falls back to an env var, simulated with an in-memory "filesystem":
files = {"/run/secrets/db/password": "s3cr3t-Pa55\n"}
env = {"DB_USER": "shop"}
def read_setting(name, file_dir="/run/secrets/db"):
path = f"{file_dir}/{name.lower()}"
if path in files:
return files[path].strip(), f"file {path}"
env_name = f"DB_{name.upper()}"
if env_name in env:
return env[env_name], f"env {env_name}"
raise KeyError(f"{name} not configured")
for setting in ["password", "user", "host"]:
try:
value, source = read_setting(setting)
print(f"{setting}: {'*' * len(value)} (from {source})")
except KeyError as err:
print("error:", err.args[0])password: *********** (from file /run/secrets/db/password)
user: **** (from env DB_USER)
error: host not configured
Warning: Never print secret values in logs, like the masked output above. And remember
kubectl describe secretshows only sizes, butkubectl get secret -o yamlshows the (decodable) data.
Test yourself
What protection does base64 encoding in a Secret provide?
- Strong encryption
- None, it is only an encoding
- It hashes the password
- It prevents kubectl from reading it
Which Secret type does an Ingress TLS section expect?
- Opaque
- kubernetes.io/tls
- kubernetes.io/basic-auth
- kubernetes.io/dockerconfigjson
What is a safe way to keep Secrets in a GitOps repository?
- Commit the YAML with stringData
- Commit them base64-encoded
- Encrypt them (Sealed Secrets/SOPS) or reference an external secret store
- Put them in a ConfigMap instead