Environment Injection Methods
Overview of Environment Injection Techniques
Kubernetes provides multiple methods to inject environment variables into pods, each serving different use cases and requirements.
1. Direct Environment Variable Injection
Static Environment Definition
apiVersion: v1
kind: Pod
metadata:
name: static-env-pod
spec:
containers:
- name: demo-container
image: ubuntu:22.04
env:
- name: APP_MODE
value: "production"
- name: MAX_CONNECTIONS
value: "100"
2. ConfigMap-Based Injection
Creating a ConfigMap
kubectl create configmap app-config \
--from-literal=DATABASE_HOST=localhost \
--from-literal=DATABASE_PORT=5432
Injecting ConfigMap Variables
apiVersion: v1
kind: Pod
metadata:
name: configmap-env-pod
spec:
containers:
- name: demo-container
image: ubuntu:22.04
envFrom:
- configMapRef:
name: app-config
3. Secret-Based Environment Injection
Creating a Secret
kubectl create secret generic db-credentials \
--from-literal=DB_USERNAME=admin \
--from-literal=DB_PASSWORD=secret
Injecting Secret Variables
apiVersion: v1
kind: Pod
metadata:
name: secret-env-pod
spec:
containers:
- name: demo-container
image: ubuntu:22.04
envFrom:
- secretRef:
name: db-credentials
Injection Methods Comparison
graph TD
A[Environment Injection Methods] --> B[Direct Injection]
A --> C[ConfigMap Injection]
A --> D[Secret Injection]
A --> E[Downward API Injection]
Injection Method Characteristics
Method |
Use Case |
Security |
Flexibility |
Direct Injection |
Simple, static configs |
Low |
Limited |
ConfigMap |
Complex configurations |
Medium |
High |
Secrets |
Sensitive data |
High |
Medium |
Downward API |
Cluster metadata |
Medium |
Specific |
4. Downward API Injection
apiVersion: v1
kind: Pod
metadata:
name: metadata-env-pod
spec:
containers:
- name: demo-container
image: ubuntu:22.04
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: CPU_LIMIT
valueFrom:
resourceFieldRef:
containerName: demo-container
resource: limits.cpu
Advanced Injection Techniques
- Dynamic environment generation
- Conditional variable injection
- Environment variable validation
LabEx Recommendation
Explore LabEx's Kubernetes environment injection labs to gain practical experience with these techniques.
Best Practices
- Use appropriate injection method for each use case
- Minimize hardcoded values
- Implement proper secret management
- Validate and sanitize injected environments