Creating Secrets
Secrets store sensitive data such as passwords, tokens, and certificates. While similar to ConfigMaps, Secrets are base64-encoded and can have stricter RBAC policies applied.
Generic Secrets (Opaque)
The most common type, used for arbitrary key-value data:
kubectl create secret generic db-credentials \
--from-literal=username=admin \
--from-literal=password=s3cureP@ss
# From files
kubectl create secret generic tls-data \
--from-file=cert.pem \
--from-file=key.pem
Docker Registry Secrets
Used to authenticate with private container registries:
kubectl create secret docker-registry my-registry \
--docker-server=registry.example.com \
--docker-username=user \
--docker-password=pass \
--docker-email=user@example.com
Reference it in a pod spec with imagePullSecrets:
spec:
imagePullSecrets:
- name: my-registry
TLS Secrets
Store a TLS certificate and private key pair:
kubectl create secret tls my-tls-secret \
--cert=tls.crt \
--key=tls.key
This creates a secret with tls.crt and tls.key data fields, commonly used by Ingress resources.
Base64 Encoding in YAML
When defining secrets in YAML, values must be base64-encoded:
echo -n 'admin' | base64
# YWRtaW4=
echo -n 's3cureP@ss' | base64
# czNjdXJlUEBzcw==
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
data:
username: YWRtaW4=
password: czNjdXJlUEBzcw==
Alternatively, use stringData to avoid manual encoding:
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
stringData:
username: admin
password: s3cureP@ss
Kubernetes automatically base64-encodes stringData values when the Secret is stored. Note that Secrets are not encrypted by default in etcd. Enable encryption at rest for production clusters.