Configuration Management: Keeping Apps Dynamic
7 min read
Configuration Management: Keeping Apps Dynamic ⚙️
Welcome to the fascinating world of Kubernetes Configuration Management! Ever tried to change a setting in your application and had to rebuild the entire container image? It's like wanting to change the salt in your soup and having to cook the whole meal again from scratch. Not very efficient, right? That's the problem we're going to solve in this section.
The Problem: Hardcoding configuration details like database URLs, API keys, or feature flags directly into your application code or container images is a recipe for disaster. It makes your application inflexible, hard to manage across different environments (development, staging, production), and a nightmare to update.
The Solution: Kubernetes provides powerful tools to decouple your configuration from your application, allowing you to manage it dynamically. This means you can update your application's behavior without rebuilding and redeploying it. Let's dive into the key players in this space: ConfigMaps and Secrets.
1. ConfigMaps: Decoupling Configuration from Container Images 📜
What is a ConfigMap?
A ConfigMap is a Kubernetes object used to store non-confidential configuration data in key-value pairs. Think of it as a dedicated configuration file for your Kubernetes cluster. Your application, running in a Pod, can then access this data.
Why do we need them?
Imagine you have a web application that connects to a database. The database URL will be different for your development, staging, and production environments. Instead of building a separate container image for each environment with the hardcoded URL, you can create a ConfigMap for each environment with the appropriate database URL. Your application then simply reads the URL from the ConfigMap, making your container image portable and your configuration manageable.
Creating a ConfigMap
You can create ConfigMaps in a few ways, but the most common is by defining a YAML file.
Let's say we have some application settings we want to manage:
app.properties:abnfgreeting=Hello farewell=Goodbye
Here’s how you can create a ConfigMap from this file:
YAML Definition (app-configmap.yaml):
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
# from literal values
log_level: "info"
# from a file
app.properties: |
greeting=Hello
farewell=GoodbyeTo create this ConfigMap, you would run:kubectl apply -f app-configmap.yaml
You can also create ConfigMaps directly from the command line, which is handy for quick tasks.
Interesting Fact: The data in a ConfigMap is not encrypted. It's stored in etcd, the key-value store of Kubernetes, in plain text. This is why you should never store sensitive information like passwords or API keys in a ConfigMap. For that, we have a more secure friend called Secrets.
2. Secrets: Safely Storing Passwords and Keys 🤫
What is a Secret?
A Kubernetes Secret is an object that lets you store and manage sensitive information, such as passwords, OAuth tokens, and ssh keys. Storing this information in a Secret is safer than putting it verbatim in a Pod definition or in a container image.
Why are they so important?
Leaving your passwords and API keys lying around in plain text in your configuration files is like leaving your house keys under the doormat. It might be convenient, but it's not secure. Secrets provide a dedicated mechanism to handle sensitive data, giving you more control over how it's used and reducing the risk of accidental exposure.
Creating a Secret
Creating Secrets is similar to creating ConfigMaps. You can use a YAML file or the command line.
Let's say we need to store a username and password for a database.
YAML Definition (db-secret.yaml):
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque # The default type, for arbitrary user-defined data
data:
# The values are base64 encoded
username: dXNlcg== # "user"
password: cGFzc3dvcmQ= # "password"Important Note: The values in a Secret's data field must be base64 encoded. This is not for encryption, but to handle binary data. Anyone with access to the Secret object can easily decode the values. True security for Secrets often involves integrating with external secret management systems like HashiCorp Vault or using Kubernetes' built-in encryption at rest features.
To create this Secret, you'd run:kubectl apply -f db-secret.yaml
You can also create a secret from literal values on the command line, and kubectl will handle the base64 encoding for you:
kubectl create secret generic db-credentials --from-literal=username=user --from-literal=password=password
3. Injecting Configs as Environment Variables 注入
Now that we have our configuration neatly stored in ConfigMaps and Secrets, how do our applications actually use this data? One of the most common ways is to inject them as environment variables into a Pod.
The Concept: When a Pod starts up, Kubernetes can read data from a ConfigMap or a Secret and make it available to the containers running inside that Pod as environment variables. Your application can then read these environment variables just like it would any other.
Example with a ConfigMap:
Let's use the app-config ConfigMap we created earlier and inject the log_level into a Pod.
Pod Definition (app-pod.yaml):
apiVersion: v1
kind: Pod
metadata:
name: my-app-pod
spec:
containers:
- name: my-app-container
image: busybox
command: [ "/bin/sh", "-c", "env" ]
env:
- name: LOG_LEVEL
valueFrom:
configMapKeyRef:
name: app-config
key: log_levelIn this example, we're creating an environment variable named LOG_LEVEL inside our container. Its value is being pulled from the app-config ConfigMap, specifically from the key log_level.
Example with a Secret:
Similarly, let's inject our database credentials from the db-credentials Secret.
Pod Definition (app-pod-with-secret.yaml):
apiVersion: v1
kind: Pod
metadata:
name: my-app-pod-with-secret
spec:
containers:
- name: my-app-container
image: busybox
command: [ "/bin/sh", "-c", "env" ]
env:
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: db-credentials
key: username
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: passwordHere, the DB_USERNAME and DB_PASSWORD environment variables will be populated with the decoded values from our db-credentials Secret.
Funny Exaggeration: Injecting configs as environment variables is like having a helpful robot assistant who whispers all the important settings into your application's ear right as it wakes up. "Psst... the database is over there, and here's the secret handshake to get in."
4. Mounting Configs as File Volumes in Pods 📁
Another powerful way to get configuration into your Pods is by mounting ConfigMaps and Secrets as volumes. This makes the data appear as files inside your container.
Why would you do this?
Sometimes, applications are designed to read configuration from files (e.g., settings.json, config.xml). Instead of rewriting your application to read from environment variables, you can simply provide the configuration as a file, right where the application expects it. This is also useful for larger configuration files or when you want to update the configuration of a running application without restarting the Pod.
Example with a ConfigMap:
Let's mount the app.properties file from our app-config ConfigMap into a Pod.
Pod Definition (app-pod-volume.yaml):
apiVersion: v1
kind: Pod
metadata:
name: my-app-pod-volume
spec:
containers:
- name: my-app-container
image: busybox
command: [ "/bin/sh", "-c", "cat /etc/config/app.properties" ]
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: app-configIn this example:
- We define a volume named
config-volumeand specify that it should be populated with the data from theapp-configConfigMap. - We then mount this volume inside our container at the path
/etc/config. - Kubernetes will create a file named
app.propertiesinside the/etc/configdirectory with the content we defined in the ConfigMap.
Example with a Secret:
Mounting a Secret as a volume works in a very similar way.
Pod Definition (app-pod-secret-volume.yaml):
apiVersion: v1
kind: Pod
metadata:
name: my-app-pod-secret-volume
spec:
containers:
- name: my-app-container
image: busybox
command: [ "/bin/sh", "-c", "ls /etc/secrets" ]
volumeMounts:
- name: secret-volume
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secret-volume
secret:
secretName: db-credentialsHere, a directory /etc/secrets will be created inside the container. Within this directory, there will be files named username and password, containing the respective decoded values from the db-credentials Secret. It's a good practice to mount secrets as readOnly.
Industry Practice: A common pattern is to mount a ConfigMap as a volume and have your application watch for changes to the file. This allows for dynamic reconfiguration of your application without needing to restart it.
Further Reading & References 📚
- Kubernetes Documentation on ConfigMaps: https://kubernetes.io/docs/concepts/configuration/configmap/
- Kubernetes Documentation on Secrets: https://kubernetes.io/docs/concepts/configuration/secret/
- Configure a Pod to Use a ConfigMap: https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/
- Managing Secrets using kubectl: https://kubernetes.io/docs/tasks/configmap-secret/managing-secret-using-kubectl/
Challenge
You are tasked with creating a set of Kubernetes manifests to configure a new application. Your goal is to externalize configuration and sensitive data using a ConfigMap and a Secret, and then consume them within a Pod.
Requirements:
Create a ConfigMap named
app-config.- It must contain two data keys:
API_ENDPOINTwith the valuehttps://api.example.com/v1LOG_LEVELwith the valueinfo
- It must contain two data keys:
Create a Secret named
db-credentialsof typeOpaque.- It must store the following data, ensuring the values are base64 encoded:
username: the base64 encoded value ofadminisYWRtaW4=password: the base64 encoded value ofsupersecretisc3VwZXJzZWNyZXQ=
- It must store the following data, ensuring the values are base64 encoded:
Create a Pod named
my-app-pod.- The Pod should contain a single container named
app-containerusing thenginx:latestimage. - Inject Configuration via Environment Variables:
- Inject the
API_ENDPOINTandLOG_LEVELvalues from theapp-configConfigMap as environment variables into theapp-container.
- Inject the
- Mount Sensitive Data as a Volume:
- Mount the
db-credentialsSecret as a read-only volume into the container at the path/etc/creds.
- Mount the
- The Pod should contain a single container named
Combine all three resource definitions into a single YAML file, separated by ---.
Expected result
Your final output should be a single, valid YAML manifest containing three Kubernetes resource definitions separated by ---.
- A
ConfigMapresource namedapp-configwith the specifieddatakeys and values. - A
Secretresource nameddb-credentialsof typeOpaque, with theusernameandpasswordkeys holding the provided base64 encoded strings. - A
Podresource namedmy-app-podwith a single containerapp-container.- The container's
envsection must correctly reference theapp-configConfigMap to set theAPI_ENDPOINTandLOG_LEVELenvironment variables. - The Pod's
volumessection must define a volume that sources its data from thedb-credentialsSecret. - The container's
volumeMountssection must mount this volume at/etc/credsand havereadOnlyset totrue.
- The container's