Some of my notes while reading about config maps and secrets in Kubernetes.
🌎 Purpose of decoupling configuration from the application, hence the existence of ConfigMaps and Secrets:
Consider the following scenario:
- You deploy a Go application to a staging environment for internal review.
- When moving to production, the PostgreSQL connection string is different.
If the database URL is hardcoded in the Go app, you’ll need to rebuild it for production.
But if the app reads its config from the environment or a file, you can swap in the new database URL without touching the code.
❗️ The application code should be independent of the infrastructure it is running on.
Think of them as repositories for key-value pairs.
- Get configmaps in your cluster:
kubectl get configmaps
- Same thing but shorter:
kubectl get cm
- Creating an empty configmap imperatively:
kubectl create cm my-first-configmap
- Creating a configmap from literal values imperatively:
# creates a key named "color" and its value is set to "blue"
kubectl create cm my-second-configmap --from-literal=color=blue
- Creating a configmap from an env file:
kubectl create cm anotherconfigmap --from-env-file=my-env-file.txt
- View the data inside the configmap:
# data in configmaps is not encrypted so use secrets for stuff you don't want public
kubectl describe cm/anotherconfigmap
- Launch a pod with an env variable taken from config map:
kubectl apply -f nginx-pod-with-configmap.yml
- See that variable for yourself:
kubectl exec pods/nginx-pod-with-configmap -- env
- In the case of a configmap mounted as a volume:
echo “I’m just a dummy config file” >> $HOME/configfile.txt
kubectl create cm my-sixth-configmap --from-literal=color=yellow --from-file=$HOME/configfile.txt
kubectl apply -f pod-with-volume-cm.yml
kubectl exec pods/nginx-pod-cm -- ls /etc/conf
- Creating a secret imperatively:
kubectl create secret generic my-first-secret --from-literal='db_pass=my_db_pass'
- Creating a secret from a file:
kubectl create secret generic mypassword --from-file=./password.txt
- Creating a pod using the secret from a file we just made:
kubectl create -f nginx-pod-with-secret-env-var.yml
- Creating a pod with envFrom secret:
kubectl create -f nginx-secret-envfrom.yml
- Seeing those env vars in person:
kubectl exec -it pod/nginx-secret-envfrom --container nginx-container -- /bin/bash
env
Lastly, note that there is no clean and consistent way to modify a secret once it has been created through kubectl.
To update a secret, you will need to delete it and then recreate it with the new values you need by following the examples given previously.