Env & ConfigMaps in Kubernetes - CKA
In modern cloud-native applications, managing configuration and sensitive data efficiently and securely is essential. Kubernetes addresses this need with ConfigMaps. ConfigMaps store non-confidential configuration data, enabling dynamic updates and easy application portability. By separating configuration and sensitive data from application code, Kubernetes enhances security, flexibility, and adherence to best practices. Let's understand these concepts better through hands-on examples.
ConfigMaps
ConfigMap is a Kubernetes resource used to store non-confidential data in key-value pairs. It allows you to decouple configuration artifacts from image content to keep containerized applications portable.
Example
Create a Pod with an Environment Variable
apiVersion: v1 kind: Pod metadata: name: myapp labels: name: myapp-pod spec: containers: - name: myapp-container image: busybox:1.28 command: ['sh', '-c', 'echo The app is running! && sleep 3600'] env: - name: FIRSTNAME value: "harshit"
The above YAML file (
pod.yaml
) creates a pod with the BusyBox image. It sets an environment variableFIRSTNAME
within the container. Apply this file and execute into the container to check the environment variable:kubectl apply -f pod.yaml kubectl exec -it myapp -- sh echo $FIRSTNAME # Output will be "harshit"
Create a ConfigMap
Next, we'll create a ConfigMap to store these values and inject it into the Pod.
kubectl create configmap app-cm --from-literal=firstname=harshit --from-literal=lastname=sahu
Inject ConfigMap into a Pod
Now, modify the Pod definition to use the ConfigMap:
apiVersion: v1 kind: Pod metadata: name: myapp labels: name: myapp-pod spec: containers: - name: myapp-container image: busybox:1.28 command: ["sh", "-c", "echo The app is running! && sleep 3600"] env: - name: FIRSTNAME valueFrom: configMapKeyRef: name: app-cm key: firstname
Apply this YAML file:
kubectl apply -f pod.yaml
When you describe the Pod, you will see that the
FIRSTNAME
environment variable is now sourced from the ConfigMap.Imperative ConfigMap Creation with file
kubectl create configmap app-cm --from-file=map.configure
Declarative ConfigMap Creation
If you have many key-value pairs, creating a ConfigMap from the command line can be cumbersome. Instead, you can create it declaratively using a YAML file. You can generate this file with an imperative command:
kubectl create configmap app-cm --from-literal=firstname=harshit --from-literal=lastname=sahu --dry-run=client -o yaml > cm.yaml
This will generate a
cm.yaml
file:apiVersion: v1 kind: ConfigMap metadata: name: app-cm data: firstname: harshit lastname: sahu
Apply this YAML file:
kubectl apply -f cm.yaml
ConfigMaps can also be used by mounting them as volumes, which we will cover in future posts in this series. You can also learn more about ConfigMaps from the official documentation.