Secrets as Environment Vars
Introduction to Secret Injection
Injecting Kubernetes Secrets as environment variables is a powerful technique for securely providing sensitive configuration to applications at runtime.
Injection Methods
graph TD
A[Secret Injection Methods] --> B[envFrom]
A --> C[env]
A --> D[Volume Mount]
Injection Techniques
1. Direct Environment Variable Injection
apiVersion: v1
kind: Pod
metadata:
name: secret-env-example
spec:
containers:
- name: app-container
image: ubuntu:22.04
env:
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: database-secret
key: username
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: database-secret
key: password
2. Bulk Secret Injection with envFrom
apiVersion: v1
kind: Pod
metadata:
name: bulk-secret-env
spec:
containers:
- name: app-container
image: ubuntu:22.04
envFrom:
- secretRef:
name: database-credentials
Environment Variable Injection Comparison
Method |
Pros |
Cons |
Individual env |
Precise control |
Manual configuration |
envFrom |
Quick bulk injection |
Less granular |
Volume Mount |
Supports large secrets |
More complex setup |
Best Practices
Security Considerations
- Avoid logging environment variables
- Use read-only file systems
- Implement secret rotation mechanisms
Example Python Application
import os
## Accessing injected secrets
db_username = os.environ.get('DB_USERNAME')
db_password = os.environ.get('DB_PASSWORD')
def connect_database():
## Use secrets for database connection
connection = create_connection(
username=db_username,
password=db_password
)
Advanced Secret Management Workflow
graph LR
A[Create Secret] --> B[Define Pod/Deployment]
B --> C[Inject as Environment Vars]
C --> D[Application Consumes Secrets]
D --> E[Rotate/Update Secrets]
Practical Demonstration
## Create a secret
kubectl create secret generic database-credentials \
--from-literal=DB_USERNAME=admin \
--from-literal=DB_PASSWORD=secure_password
## Apply pod configuration
kubectl apply -f secret-env-pod.yaml
LabEx Recommendations
LabEx encourages developers to implement secure secret injection practices, emphasizing the importance of protecting sensitive configuration in cloud-native environments.
Common Pitfalls to Avoid
- Hardcoding secrets in source code
- Exposing secrets in logs
- Using overly permissive RBAC policies
- Neglecting secret rotation
By mastering secret injection as environment variables, developers can create more secure and flexible Kubernetes applications.