#
ConfigMaps explanation
This tutorial explains how a ConfigMaps could be used in Kubernetes.
ConfigMaps is an object used in Kubernetes to store data in key-value pairs. It's essentially a dictionary that contains configuration settings.
Info
ConfigMaps doesn't encrypt the data in it. If you want to keep encrypted data, we can use Secrets. If you have some critical data like keys, passwords, service accounts credentials, DB connection string, etc then you should always go for Secrets rather than Configs.
ConfigMaps in Kubernetes can be consumed in different ways:
- mounting it as a volume
- consumption via environment variables
- consumption via command-line arguments
ConfigMaps in Kubernetes can be created in different ways as well:
- from a file which keeps the key/value pairs
- from a ConfigMap object yaml file definition
We consider the following text file (properties.txt) :
database=oracle
host.name=linux1
We can create a ConfigMap named config-map-1-dev from this file, using the following command:
kubectl create configmap config-map-1-dev --from-file properties.txt
If we want to view the data in a ConfigMap via console output, we can use the following command:
kubectl describe configmaps config-map-1-dev
If we run this command we can see:
Name: config-map-1-dev
Namespace: default
Labels: <none>
Annotations: <none>
Data
====
properties.txt:
----
database=oracle\r
host.name=linux1
BinaryData
====
Events: <none>
We can create a ConfigMap object yaml file as below and use it for creating another ConfigMap named config-map-2-dev.
Consider the following config-map-2-dev.yaml file:
apiVersion: v1
kind: ConfigMap
metadata:
name: config-map-2-dev
data:
# key/value format
remote-database: "mongodb"
remote-host: "linux2"
# file-like keys
application.properties: |
server.port=8080
service.maximum-instance=3
We can create a ConfigMap named config-map-2-dev from this file, using the following command:
kubectl apply -f config-map-2-dev.yaml
If we need to see the ConfigMaps we have created, we can run the following command:
kubectl get configmaps
On my side, I can see the following result of the command:
NAME DATA AGE
config-map-1-dev 1 16m
config-map-2-dev 3 38s
kube-root-ca.crt 1 4d15h
Now we can create a pod to let it use some of these values defined in ConfigMaps:
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
zone: dev
version: v1
spec:
containers:
- name: nginx-c
image: nginx:1.14.2
ports:
- containerPort: 8080
env:
- name: DATABASE_TYPE
valueFrom:
configMapKeyRef:
name: config-map-1-dev
key: database
- name: SERVER_PORT
valueFrom:
configMapKeyRef:
name: config-map-2-dev
key: server.port
We can create the pod by running the following command:
kubectl apply -f configmaps-pod.yaml
At this point what is running into nginx-c container could have access to the DATABASE_TYPE and SERVER_PORT environment variable.
If we want to delete a ConfigMap we can run the following command:
kubectl delete configmap config-map-2-dev