tezvyn:

Kubernetes: Inject ConfigMaps & Secrets as Env Vars

AI-drafted, machine-checkedSource: kubernetes.iobeginner
Kubernetes: Inject ConfigMaps & Secrets as Env Vars

Injecting ConfigMaps and Secrets as environment variables decouples your app from its configuration. Kubernetes passes these key-value pairs into your container at startup, perfect for things like API keys or feature flags.

WHY IT EXISTS: To prevent hardcoding configuration like database URLs or API keys into a container image. An image should be an immutable, reusable artifact. By externalizing configuration, you can deploy the same image to development, staging, and production, each with its own settings, without rebuilding the image.

THE MENTAL MODEL: Think of your Pod manifest as a startup script for your application. Injecting environment variables from a ConfigMap or Secret is like setting export API_KEY="value" in a shell script right before running your program. The application inside the container just reads from its environment, completely unaware of Kubernetes, ConfigMaps, or Secrets.

HOW IT WORKS: In your Pod specification, you define an env or envFrom section for a container. With env, you map a single key from a ConfigMap or Secret to a specific environment variable name. With envFrom, you can inject all key-value pairs from the source object at once. At Pod creation, Kubernetes reads the referenced object and injects the values into the container's environment before its main process starts.

WHEN TO USE IT: This is the simplest and most common way to get configuration into a Pod. It's ideal for a small to moderate number of configuration values that your application is designed to read from the environment. It works for both non-sensitive data (from ConfigMaps) and sensitive data (from Secrets).

WHEN NOT TO USE IT: Do not use this method if you need configuration to be updated dynamically without a Pod restart; for that, mount the ConfigMap or Secret as a volume instead. Also, avoid this for very large configuration files or binary data. Be cautious when injecting Secrets this way, as any process in the container can easily inspect all environment variables, potentially exposing sensitive data.

ONE CANONICAL EXAMPLE: A web application needs a database connection URL. You create a Secret named db-credentials containing the key POSTGRES_URL. In your Pod definition, you specify that you want an environment variable named DATABASE_URL inside the container, and its value should come from the POSTGRES_URL key in the db-credentials Secret. When the Pod starts, the application can connect to the database by reading the DATABASE_URL environment variable, without the connection string ever being in the container image.

Read the original → kubernetes.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.