Kubernetes offers robust tools for managing application configurations and safeguarding sensitive data: ConfigMaps and Secrets. This article provides hands-on examples to help you grasp these concepts.
What are ConfigMaps?
ConfigMaps in Kubernetes are designed to manage non-sensitive configuration data. They are generally created using YAML files that specify the configuration parameters.
Example: Environment Variables
Consider an application that requires a database URL and an API key. You can use a ConfigMap to set these as environment variables. Here’s a sample YAML file:
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
DB_URL: jdbc:mysql://localhost:3306/db
API_KEY: key123
Mounting ConfigMaps as Volumes
ConfigMaps can also be mounted as volumes, making them accessible to pods as files. This is useful for configuration files or scripts.
Example: Mount as Volume
To mount a ConfigMap as a volume, you can modify the pod specification like this:
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: my-image
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: app-config
What are Secrets?
Secrets are used for storing sensitive information like passwords and API tokens securely. It’s important to note that the data in Secrets should be encoded in base64 for an added layer of security.
Example: Secure API Token
To store an API token securely, you can create a Secret like this:
apiVersion: v1
kind: Secret
metadata:
name: api-secret
data:
API_TOKEN: base64_encoded_token
To generate a base64-encoded token, you can use the following command:
echo -n 'your_actual_token' | base64
In Summary
ConfigMaps and Secrets are indispensable tools in Kubernetes for managing configuration data and sensitive information. Understanding how to use them effectively is crucial for any Kubernetes deployment.