Lesson 6.1: ConfigMaps
In Kubernetes, ConfigMaps are used to manage configuration data as key-value pairs. They allow you to decouple configuration from application code, making it easier to manage and update configurations without modifying the application itself. There are two main ways to create and use ConfigMaps:
- Imperative Way: Using kubectl create configmap commands.
- Declarative Way: Using YAML manifests.
Imperative Way
In the imperative approach, you use kubectl commands to create and manage ConfigMaps directly from the command line.
[root@master confsec]# kubectl create cm app-cm --from-literal=firstname=sanjeeb --from-literal=lastname=kc
configmap/app-cm created
[root@master confsec]# kubectl get cm
NAME DATA AGE
app-cm 2 4s
kube-root-ca.crt 1 6d5h
[root@master confsec]# kubectl describe cm app-cm
Name: app-cm
Namespace: default
Labels: <none>
Annotations: <none>
Data
====
firstname:
----
sanjeeb
lastname:
----
kc
BinaryData
====
Events: <none>
# Create a Pod YAML file (pod.yml) that references the ConfigMap
[root@master confsec]# cat pod.yml
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
name: myapp
spec:
containers:
- name: nginx-container
image: nginx:latest
env:
- name: FIRSTNAME
valueFrom:
configMapKeyRef:
name: app-cm
key: firstname
[root@master confsec]# kubectl exec -it nginx-pod -- sh
# echo $FIRSTNAME
sanjeeb
# exit
- env: Defines environment variables for the container.
- valueFrom.configMapKeyRef: References a specific key (firstname) from the ConfigMap (app-cm).
Declarative Way
In the declarative approach, you define the ConfigMap and Pod in YAML files and apply them using kubectl apply.
[root@master confsec]# kubectl create cm app-cm --from-literal=firstname=John --from-literal=lastname=Doe --dry-run=client -o yaml > cm.yml
[root@master confsec]# cat cm.yml
apiVersion: v1
data:
firstname: John
lastname: Doe
kind: ConfigMap
metadata:
creationTimestamp: null
name: app-cm
[root@master confsec]# cat pod.yml
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
name: myapp
spec:
containers:
- name: nginx-container
image: nginx:latest
envFrom:
- configMapRef:
name: app-cm
[root@master confsec]# kubectl apply -f cm.yml
configmap/app-cm created
[root@master confsec]# kubectl apply -f pod.yml
pod/nginx-pod created
[root@master confsec]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-pod 1/1 Running 0 4s
[root@master confsec]#
[root@master confsec]# kubectl get cm
NAME DATA AGE
app-cm 2 85s
[root@master confsec]# kubectl exec -it nginx-pod -- sh
# echo $firstname
John
# echo $lastname
Doe
# exit