ConfigMap Keys as Environment Variable Names
What you'll learn: How to map individual ConfigMap keys directly to specific environment variable names in your Pods using valueFrom and configMapKeyRef.
The Core Idea
So far, you've seen how to inject entire ConfigMaps as environment variables (using envFrom). But what if you only need one or two specific keys from a ConfigMap, or you want to give them custom environment variable names? That's where valueFrom and configMapKeyRef come in.
Instead of importing all ConfigMap data at once, you can cherry-pick individual keys and map them to precise environment variable names. This gives you fine-grained control over your Pod's environment.
How It Works
In your Pod spec, under env, you define each environment variable explicitly. Instead of setting a static value, you use valueFrom to reference a specific key from a ConfigMap:
env:
- name: DATABASE_HOST
valueFrom:
configMapKeyRef:
name: app-config
key: db.host
- name: MAX_CONNECTIONS
valueFrom:
configMapKeyRef:
name: app-config
key: max_conn
Here, the key db.host from the app-config ConfigMap becomes the environment variable DATABASE_HOST, and max_conn becomes MAX_CONNECTIONS. You control both the source key and the destination variable name.
When to Use This Approach
This pattern is ideal when:
- You need only a subset of ConfigMap data
- You want meaningful, app-specific variable names
- Multiple ConfigMaps contribute to the same Pod's environment
Key Takeaway: Use valueFrom with configMapKeyRef to selectively map individual ConfigMap keys to custom environment variable names, giving you precise control over your Pod's configuration.