0

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"}}' \
    http://localhost:8001/api/v1/namespaces/default/configmaps

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?

xpepermint
  • 267
  • 3
  • 9

1 Answers1

2

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"

Mike Bryant
  • 161
  • 2