In this lesson, we will explore how to manage configuration data and sensitive information in Kubernetes using ConfigMaps and Secrets. These resources allow you to decouple environment-specific configurations from your application code, enhancing security and flexibility.
A ConfigMap is a Kubernetes resource that allows you to store non-sensitive configuration data in key-value pairs. ConfigMaps can be used to configure applications without the need to rebuild container images.
You can create a ConfigMap from literal values, files, or directories. Here’s how to create a ConfigMap from literal values:
kubectl create configmap my-config --from-literal=app.mode=production --from-literal=app.version=1.0
You can use a ConfigMap as environment variables or as volumes in your Pods. Here’s an example of how to use it as environment variables:
apiVersion: v1
kind: Pod
metadata:
name: my-app
spec:
containers:
- name: my-container
image: my-image
env:
- name: APP_MODE
valueFrom:
configMapKeyRef:
name: my-config
key: app.mode
- name: APP_VERSION
valueFrom:
configMapKeyRef:
name: my-config
key: app.version
A Secret is similar to a ConfigMap, but it is specifically intended to hold sensitive data, such as passwords, OAuth tokens, and SSH keys. Secrets are encoded in base64 to provide a layer of security.
You can create a Secret using literal values or from files. Here’s how to create a Secret from literal values:
kubectl create secret generic my-secret --from-literal=username=admin --from-literal=password=secret123
You can use Secrets as environment variables or as volumes in your Pods. Here’s an example of how to use a Secret as environment variables:
apiVersion: v1
kind: Pod
metadata:
name: my-secure-app
spec:
containers:
- name: secure-container
image: secure-image
env:
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: my-secret
key: username
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: my-secret
key: password
Always use Secrets for sensitive data. ConfigMaps should not be used for storing sensitive information.
Limit access to Secrets. Use Kubernetes RBAC to restrict who can view or modify Secrets.
Avoid hardcoding values. Instead of hardcoding sensitive information in your application code, use environment variables or configuration files.
app-config with the keys database.url and database.port.db-credentials with the keys username and password, and use it in a Pod definition.app-config ConfigMap as an environment variable.