Secret Basics in K8s
What are Kubernetes Secrets?
Kubernetes Secrets are objects that help manage sensitive information such as passwords, OAuth tokens, SSH keys, and other confidential data. They provide a way to separate sensitive configuration data from container images and pod specifications, enhancing security and flexibility in application deployment.
Types of Kubernetes Secrets
Kubernetes supports several types of secrets to accommodate different use cases:
Secret Type |
Description |
Use Case |
Opaque |
Default secret type |
Generic key-value pairs |
Docker Registry |
Store Docker registry credentials |
Pulling private images |
TLS |
Store TLS certificates |
HTTPS and secure communications |
Service Account |
Automatically created tokens |
Authenticating with API server |
Secret Creation Mechanisms
Secrets can be created through multiple methods:
graph TD
A[Secret Creation Methods] --> B[kubectl command]
A --> C[YAML Configuration]
A --> D[Kubernetes API]
A --> E[Helm Charts]
1. Using kubectl Command
Create a secret directly from the command line:
## Create a generic secret
kubectl create secret generic db-credentials \
--from-literal=username=admin \
--from-literal=password=mysecretpassword
## Create a secret from a file
kubectl create secret generic ssl-cert \
--from-file=tls.crt=server.crt \
--from-file=tls.key=server.key
2. YAML Configuration
Define secrets in a YAML file for version-controlled deployment:
apiVersion: v1
kind: Secret
metadata:
name: my-secret
type: Opaque
stringData:
username: admin
password: mysecretpassword
Secret Encoding
Secrets are base64 encoded to ensure safe storage and transmission:
## Encode a value
echo -n "mysecretpassword" | base64
## Decode a value
echo "bXlzZWNyZXRwYXNzd29yZA==" | base64 --decode
Key Considerations
- Secrets are namespace-scoped
- Maximum secret size is 1MB
- Secrets are stored in etcd and can be encrypted at rest
- Avoid committing secrets to version control systems
Use Cases
- Database connection credentials
- API keys and tokens
- TLS certificates
- Docker registry authentication
By understanding these basics, you can effectively manage sensitive information in your Kubernetes clusters with LabEx's recommended best practices.