I have following configmaps
apiVersion: v1
kind: ConfigMap
metadata:
name: test
data:
application.properties: |+
key1: value1
key2: value2
keyN: valueN
Configmaps is mounted to pod and works fine.
My requirement is to programmatically replace the value for some of the keys. I can run shell/python script and I can run any kubectl command.
You can use kubectl patch
command to update K8s resources.
kubectl patch configmap/test \
--type=json \
'-p=[{"op": "replace","path": "/data/key1", "value": "test1"}]'
An important point to note as mentioned by Henry is that the application also has to re-read the properties after they have been changed.
You can use Bash
script to dynamically replace some keys and values in your ConfigMaps
.
I've created simple bash script to illustrate how it may works on my kubeadm cluster v1.20:
#!/bin/bash
keyName="key1"
value="value100"
read -p 'Enter ConfigMap name: ' configmapName
if kubectl get cm ${configmapName} 1> /dev/null 2>&1; then
echo "ConfigMap name to modify: ${configmapName}"
else
echo "ERROR: bad ConfigMap name"
exit 1
fi
kubectl patch cm ${configmapName} -p "{\"data\":{\"${keyName}\":\"${value}\"}}"
In the above example you need to pass ConfigMap
name and set what you want to modify.<br>
In addition you may want to pass keyName
and value
values as command line arguments in similar way to configmapName
value.
You can see an example of how the above script works:<br>
root@kmaster:~# ./replaceValue.sh
Enter ConfigMap name: test
ConfigMap name to modify: test
configmap/test patched
root@kmaster:~# kubectl describe cm test
Name: test
Namespace: default
Labels: <none>
Annotations: <none>
Data
====
application.properties:
----
key1:
----
value100
key2:
----
value2
keyN:
----
valueN
Events: <none>
root@kmaster:~#
Note: If you want to use kubectl replace
instead of kubectl patch
, you can use below command (e.g. sourceValue="key1: value1"
and destinationValue="key1: value100"
)<br>
kubectl get cm ${configmapName} -o yaml | sed "s/${sourceValue}/${destinationValue}/" | kubectl replace -f -