K8s Reference Patterns
Overview of Kubernetes Environment Variable References
Kubernetes provides multiple patterns for referencing and managing environment variables, enabling flexible and secure configuration management.
ConfigMap References
Creating ConfigMap
## Create ConfigMap from literal values
kubectl create configmap app-config \
--from-literal=DATABASE_HOST=mysql \
--from-literal=LOG_LEVEL=info
Referencing ConfigMap in Pod
apiVersion: v1
kind: Pod
metadata:
name: app-pod
spec:
containers:
- name: myapp
image: myapp:latest
env:
- name: DATABASE_HOST
valueFrom:
configMapKeyRef:
name: app-config
key: DATABASE_HOST
Secret References
Creating Secrets
## Create secret from literal values
kubectl create secret generic db-credentials \
--from-literal=USERNAME=admin \
--from-literal=PASSWORD=secure-password
Referencing Secrets in Pod
apiVersion: v1
kind: Pod
metadata:
name: db-app
spec:
containers:
- name: database-app
image: database:latest
env:
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: db-credentials
key: USERNAME
Reference Patterns Comparison
Pattern |
Use Case |
Pros |
Cons |
Direct Injection |
Simple configurations |
Easy to implement |
Less flexible |
ConfigMap |
Non-sensitive data |
Flexible, versioned |
Requires manual updates |
Secrets |
Sensitive data |
Encrypted at rest |
More complex management |
Advanced Reference Strategies
graph TD
A[Environment Variable References] --> B[ConfigMap]
A --> C[Secrets]
A --> D[Dynamic Injection]
B --> E[Whole ConfigMap]
B --> F[Specific Keys]
C --> G[Mounted as Volume]
C --> H[Specific Secret Keys]
- Use environment-specific configurations
- Separate sensitive and non-sensitive data
- Implement least privilege access
- Regularly rotate credentials
Validation and Debugging
## Verify pod environment variables
kubectl exec pod-name -- env
## Describe pod for configuration details
kubectl describe pod pod-name
Security Considerations
- Encrypt data at rest
- Use RBAC for secret access
- Minimize direct credential exposure
- Implement external secret management systems