apiVersion: v1
kind: ConfigMap
metadata:
name: simple-config
namespace: default
data:
portNumber: "8080"
name: Ricky
settings.env: |
someVariable=5
anotherName=blah
Save the above YAML into a file called simple-config.yaml
and create it by running kubectl apply -f simple-config.yaml
.
To see the details of the ConfigMap you create, you can use the describe
command:
$ kubectl describe cm simple-config
Name: simple-config
Namespace: default
Labels: <none>
Annotations:
Data
====
name:
----
Ricky
portNumber:
----
8080
settings.env:
----
someVariable=5
anotherName=blah
Events: <none>
For Pod to use the values from the ConfigMap, both Pod and ConfigMap need to reside in the same namespace. You can mount a ConfigMap to your Pod and use the values in one of the following ways:
Let's create a Pod and show how to consume the values from a ConfigMap.
apiVersion: v1
kind: Pod
metadata:
name: config-pod
labels:
app.kubernetes.io/name: config-pod
spec:
containers:
- name: config
image: busybox
command: ["sh", "-c", "sleep 3600"]
env:
- name: FIRST_NAME
valueFrom:
configMapKeyRef:
name: simple-config
key: name
- name: PORT_NUMBER
valueFrom:
configMapKeyRef:
name: simple-config
key: portNumber
We are using the valueFrom
and configMapKeyRef
to specify where the value for the environment variable is coming from. The environment variable name (e.g. FIRST_NAME
) is and can be different from the key name stored in the ConfigMap (e.g. name
or portNumber
).
Save the above YAML in config-pod-1.yaml
and create the Pod with kubectl apply -f config-pod-1.yaml
. Once the Pod is running, let's get the terminal inside the container and look at the environment variables:
$ kubectl exec -it config-pod -- /bin/sh
/ # env
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_SERVICE_PORT=443
HOSTNAME=config-pod
SHLVL=1
HOME=/root
PORT_NUMBER=8080
TERM=xterm
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
FIRST_NAME=Ricky
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_SERVICE_HOST=10.96.0.1
PWD=/
Notice the PORT_NUMBER
and FIRST_NAME
environment variables values are coming from the ConfigMap.
How about the values under the settings.env
key? Let's mount that as a file inside the Pod.
Here's the updated YAML for the config-pod
: