Etcd has a concept of Atomic Compare-and-Update by comparing the key's value before executing an update. I'd like to use this feature for updating a ConfigMap in my Kubernetes cluster. I'd like to update the config map only if the existing config map data or a specific data key matches a certain value.

Example ConfigMap:

curl -X POST -H 'Content-Type: application/json' \
    -d '{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "test"}, "data": {"foo": "1"}}' \

I need to interact with K8S API or directly with K8S's etcd directly if possible (is it?), and I don't want to rely on resourceVersion. I'd like to depend on my own version which is actually the config map's data key. How can I achieve such an atomic UPDATE (or DELETE) operation?


You can do this using jsonpatch

The jsonpatch test operation can compare arbitrary keys to values (including the same, or a different key), and then the update will only happen if the test passes.

Here's an example using kubectl:

m@spore:~$ k get cm test -o yaml
apiVersion: v1
  field1: a
  field2: b
kind: ConfigMap
  creationTimestamp: "2021-01-19T12:34:16Z"
  name: test
  namespace: default
  resourceVersion: "1205425"
  selfLink: /api/v1/namespaces/default/configmaps/test
  uid: bf6edcb6-0854-4e13-b635-3e298b90f73a
m@spore:~$ k patch configmap test --type=json --patch='[{"op": "test", "path": "/data/field1", "value": "b"}, {"op": "replace", "path": "/data/field2", "value": "d"}]'
The request is invalid
m@spore:~$ k get cm test -o yaml | grep field
  field1: a
  field2: b
m@spore:~$ k patch configmap test --type=json --patch='[{"op": "test", "path": "/data/field1", "value": "a"}, {"op": "replace", "path": "/data/field2", "value": "d"}]'
configmap/test patched
m@spore:~$ k get cm test -o yaml | grep field
  field1: a
  field2: d

This can also be done with the raw HTTP api of course, using -XPATCH -H "Content-Type: application/json-patch+json"

  • Yes, jsonpatch does the trick! – xpepermint Jan 19 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.