NierYYDS / K8S-ImageReplacer-AdmissionWebhook

k8s container image replacer admission webhook
1 stars 0 forks source link

The returned jsonpatch data is too verbose. #4

Open NierYYDS opened 5 months ago

NierYYDS commented 5 months ago

containers data in pod spec has a lot of key/values which has nothing to do with image replacement.

here is the contaienrs data examples, this webhook only change the image in each container.


              "containers": [
                    {
                        "command": [
                            "/bin/bash",
                            "-c",
                           "sleep 60"
                        ],
                        "env": [
                            {
                                "name": "CONFIG_FILE",
                                "value": "/etc/config/config.yaml"
                            },
                            {
                                "name": "FOO",
                                "value": "BAR"
                            }
                        ],
                        "image": "busybox",
                        "imagePullPolicy": "Always"
                     }
               ]

the code to generate this jsonpatch will return all of the containers data, but I just need the diff data of image.

        # 遍历所有容器,修改镜像名称
        containers = req_obj["spec"]["containers"]
        origin_containers = copy.deepcopy(containers)
        replace_container_image(containers)
        # 遍历init容器
        init_containers = req_obj["spec"].get("initContainers", [])
        origin_init_containers = copy.deepcopy(init_containers)
        replace_container_image(init_containers)
        # 如果容器没有变化,则直接返回
        if (
            containers == origin_containers
            and init_containers == origin_init_containers
        ):
            logging.info("req_uid=%s, No changes to the pod spec were made.", req_uid)
            return AdmissionReviewResponse(response=Response(uid=req_uid, allowed=True))

        # 构造patch
        patch = [{"op": "replace", "path": "/spec/containers", "value": containers}]
NierYYDS commented 5 months ago

consider using jsonpatch

>>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
>>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
>>> patch = jsonpatch.JsonPatch.from_diff(src, dst)

# or equivalently
>>> patch = jsonpatch.make_patch(src, dst)