Kubernetes API: Compare and update config map key

Solution 1:

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
data:
  field1: a
  field2: b
kind: ConfigMap
metadata:
  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
m@spore:~$ 

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