Injecting Configuration: ConfigMaps & Secrets
The golden rule of modern software development is: build once, deploy anywhere. When you create a Docker image for your Python application, that exact same image should run in your Development, Staging, and Production environments without being rebuilt.
But if the image is identical, how does the application know to connect to the test database in Staging, and the live database in Production? The answer is externalized configuration. In container orchestration systems like Kubernetes, we manage this using ConfigMaps and Secrets.
- Why hardcoding configuration violates the 12-Factor App methodology.
- How to use ConfigMaps to inject plain-text configuration (like URLs and ports).
- How to use Secrets to securely inject sensitive data (like passwords and API keys).
- The difference between injecting data as Environment Variables versus Volume Mounts.
1. The Problem with Hardcoding Configuration
In the early days of development, it is tempting to write your database URL or API token directly into your Python code or your Dockerfile. This is a dangerous anti-pattern. If you hardcode a database password into your code, anyone with access to your Git repository can read it. If you bake it into a Dockerfile, anyone who downloads your image can extract it.
Externalizing configuration means your code expects to be handed its settings from the outside world when it starts up.
| Approach | Security | Flexibility |
|---|---|---|
| Hardcoded in Code | Very Low (Exposed in Git) | Requires code changes and rebuilds to update. |
| Baked in Dockerfile | Low (Exposed in Image layers) | Requires a new Docker build for every environment. |
| ConfigMaps & Secrets | High (Managed by the cluster) | Zero rebuilds. Just swap the config payload. |
2. ConfigMaps for Non-Sensitive Data
A ConfigMap is a Kubernetes object used to store non-confidential data in key-value pairs. Think of it as a dictionary that lives inside your cluster. You use it for things like log levels, application ports, or external service URLs.
Creating and Consuming a ConfigMap
Example 1: Kubernetes ConfigMap YAML
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
LOG_LEVEL: "DEBUG"
DATABASE_HOST: "postgres-svc.default.svc.cluster.local"
When you deploy your application, you tell Kubernetes to grab these values and inject them into your container as environment variables. In your Python application, you simply read them from the operating system.
Example 2: Reading Config in Python
import os
# Read the injected environment variables
log_level = os.environ.get("LOG_LEVEL", "INFO")
db_host = os.environ.get("DATABASE_HOST", "localhost")
print(f"Starting app with Log Level: {log_level}")
print(f"Connecting to DB at: {db_host}")
"INFO"). This is a best practice. If the ConfigMap fails to mount, your app won't instantly crash; it will fall back to a safe default.3. Secrets for Sensitive Data
A Secret works almost exactly like a ConfigMap, but it is specifically designed for confidential data like passwords, OAuth tokens, and SSH keys. Kubernetes stores Secrets slightly differently under the hood to reduce the risk of accidental exposure.
Example 3: Kubernetes Secret YAML
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
data:
# Values in Secrets MUST be Base64 encoded in the YAML
DB_PASSWORD: c3VwZXJzZWNyZXRwYXNzd29yZA==
4. Architecture / Workflow Visualized
How does the data actually get from the Kubernetes cluster into your running Python script? The orchestration system intercepts the deployment process and maps the data directly into the container's memory or file system.
Configuration Injection Flow
The orchestration agent (Kubelet) reads the ConfigMap and Secret from the cluster database and injects them into the Pod just before the Python container starts.
5. Step-by-Step Execution Breakdown
There are two primary ways to inject this data into your container. Here is exactly what happens under the hood when a pod spins up:
The orchestration engine starts the container and maps the key-value pairs directly into the container's environment space. Your Python app reads them instantly via
os.environ. This is great for simple strings and tokens.Instead of environment variables, the orchestrator creates a temporary file system (tmpfs) mounted into a directory like
/etc/secrets/. The keys become filenames, and the values become the file contents. Your Python app reads them using standard file operations (e.g., open('/etc/secrets/DB_PASSWORD').read()).If you update a ConfigMap that is injected as an environment variable, the running container will not see the change. You must restart the pod. However, if it is mounted as a Volume, Kubernetes will eventually update the file while the container is running!
6. Hands-On Practice
Test your understanding of externalized configuration with these exercises.
Write a Python snippet that attempts to read an environment variable named API_TIMEOUT. If it does not exist, it should safely default to the integer 30.
Hint: Remember that os.environ.get() always returns a string, so you must convert it to an integer using int().
You need to put the password P@ssw0rd2026! into a Kubernetes Secret YAML. Open your terminal (or Python shell) and generate the Base64 encoded string.
Expected result: You can use Python: import base64; print(base64.b64encode(b"P@ssw0rd2026!")) to get the correct string for your YAML.
Assume a Kubernetes Secret has been volume-mounted to /run/secrets/api_token. Write a Python function that securely reads this file, strips any trailing whitespace or newline characters, and returns the token.
Hint: Use a context manager (with open(...)) and the .strip() string method.
7. Interview Questions
If you are interviewing for a Backend, DevOps, or Site Reliability Engineering (SRE) role, you are guaranteed to be asked about configuration management.
Answer: No. By default, Kubernetes Secrets are merely Base64 encoded, which is a format conversion, not encryption. Anyone with access to the cluster or the etcd data store can decode them easily. To make them truly secure, a cluster administrator must explicitly enable "Encryption at Rest" for the etcd database, or the team should integrate an external secrets manager like AWS KMS or HashiCorp Vault.
Answer: The 12-Factor App methodology mandates that strict separation of config from code must be maintained, and configuration should be stored in the environment (Environment Variables). This ensures that the code repository does not contain sensitive data and that the deployment artifact (the Docker image) remains completely environment-agnostic.
Conclusion
Hardcoding data is a habit born out of convenience, but it scales terribly. By mastering ConfigMaps and Secrets, you decouple your application's logic from its operational environment. Your Python containers become portable, secure, and ready to be promoted from testing to production without a single line of code changing.
Official Documentation
- Kubernetes Documentation – ConfigMaps
- Kubernetes Documentation – Secrets
- The Twelve-Factor App – Config
Upgradix by Shrash Studio – Learn Technology. Build Your Future.