A Secret in Kubernetes is an object that stores sensitive information such as passwords, tokens, SSH keys, or certificates, separate from application code. Unlike ConfigMaps, Secrets are intended for confidential data and can be handled more securely.
⚙️ Definition
A Secret allows you to inject sensitive data into Pods without exposing it in container images, YAML files, or logs.
🧩 Why Use a Secret
- Keeps credentials out of your codebase.
- Enables secure sharing of keys and passwords between containers and Pods.
- Supports automatic injection into environment variables or files.
🧾 Example 1: Literal Secret
apiVersion: v1
kind: Secret
metadata:
name: my-secret
type: Opaque
data:
username: YWRtaW4= # base64 for "admin"
password: MWYyZDFlMmU2N2Rm # base64 for "1f2d1e2e67df"
Note: All values in a Secret must be base64-encoded.
Example encoding:
echo -n "admin" | base64 # Output: YWRtaW4=
🧾 Example 2: Secret from Literal
kubectl create secret generic my-secret \
--from-literal=username=admin \
--from-literal=password=pass123
Kubernetes automatically encodes the values.
🧰 Using a Secret in a Pod
1. As Environment Variables
apiVersion: v1
kind: Pod
metadata:
name: secret-env-pod
spec:
containers:
- name: app
image: busybox
env:
- name: USERNAME
valueFrom:
secretKeyRef:
name: my-secret
key: username
- name: PASSWORD
valueFrom:
secretKeyRef:
name: my-secret
key: password
command: ["sh", "-c", "echo Username=$USERNAME, Password=$PASSWORD"]
2. As Mounted Files
apiVersion: v1
kind: Pod
metadata:
name: secret-volume-pod
spec:
containers:
- name: app
image: busybox
command: ["cat", "/etc/secret/password"]
volumeMounts:
- name: secret-volume
mountPath: /etc/secret
readOnly: true
volumes:
- name: secret-volume
secret:
secretName: my-secret
Result: Secrets appear as files in /etc/secret/
, one file per key.
🔐 Types of Secrets
Type | Description |
---|---|
Opaque | Generic secret (default, arbitrary key-value pairs) |
kubernetes.io/service-account-token | Auto-generated token for a ServiceAccount |
kubernetes.io/dockercfg / docker-registry | Docker credentials for private registries |
kubernetes.io/tls | Stores TLS certificates and private keys |
🧠 Best Practices
- Never store plaintext secrets in code or ConfigMaps.
- Use RBAC to restrict access to Secrets.
- Enable encryption at rest for Secrets in
etcd
. - Use environment variables or mounted files — avoid printing secrets in logs.
- Rotate secrets regularly for security.
🔄 Secret vs ConfigMap
Feature | ConfigMap | Secret |
---|---|---|
Intended Data | Non-sensitive | Sensitive (passwords, keys) |
Storage | Plain text | Base64-encoded, can be encrypted |
Use Cases | App configs | Credentials, tokens, TLS certificates |
Injection | Env vars, volumes | Env vars, volumes |
🚀 Common Use Cases
- Database credentials
- API tokens or keys
- TLS certificates and private keys
- Docker registry credentials