Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

patch_namespaced_config_map with dict can't get desire result #2305

Open
mqray opened this issue Nov 13, 2024 · 2 comments
Open

patch_namespaced_config_map with dict can't get desire result #2305

mqray opened this issue Nov 13, 2024 · 2 comments
Labels
kind/bug Categorizes issue or PR as related to a bug.

Comments

@mqray
Copy link

mqray commented Nov 13, 2024

What happened (please include outputs or screenshots):
I want to update cm with this dict
now, I just want to edit cm by dict:

{
"data":
 "time":
    "old": 1234
    "new": 2345
}

and the code is:

def execute():
    k8s_config.load_kube_config()
    config_map_name = "mss-deliver"
    namespace = "platform"

    data = {
        "data": {
            "time": {
                "old": 1234,
                "new": 2345
            }
        }
    }
    # data = {"old2": "123456", "new2": "2345678"}
    # config_map_data = {'data': {"time": str(data)}}
    # config_map_data = {'data': {'key.name': 'value12346666', 'key2': 'values111111111111', 'abc': {'name': "czx"}}}
    api_instance = client.CoreV1Api()
    # Use client.V1ConfigMap instead of the python dict
    object_meta = client.V1ObjectMeta(name=config_map_name, namespace=namespace)
    body = client.V1ConfigMap(
        api_version="v1", kind="ConfigMap", metadata=object_meta, data=data)
    api_instance.patch_namespaced_config_map(name=config_map_name, namespace=namespace, body=body)

if __name__ == "__main__":
    execute()

error code like that:

HTTP response headers: HTTPHeaderDict({'Audit-Id': '26dc66b8-5479-4466-a79b-fff49d7bf4b3', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'X-Kubernetes-Pf-Flowschema-Uid': '8017a5aa-8696-457f-bae8-71e08aad4363', 'X-Kubernetes-Pf-Prioritylevel-Uid': '9c3f4694-cd35-4a4a-90a7-2a53c8cd5d07', 'Date': 'Tue, 12 Nov 2024 18:19:08 GMT', 'Content-Length': '574'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":" \"\" is invalid: patch: Invalid value: \"map[apiVersion:v1 data:map[data:map[time:map[new:2345 old:1234]]] kind:ConfigMap metadata:map[name:mss-deliver namespace:platform]]\": unrecognized type: string","reason":"Invalid","details":{"causes":[{"reason":"FieldValueInvalid","message":"Invalid value: \"map[apiVersion:v1 data:map[data:map[time:map[new:2345 old:1234]]] kind:ConfigMap metadata:map[name:mss-deliver namespace:platform]]\": unrecognized type: string","field":"patch"}]},"code":422}

and I tried to patch with

def execute():
    k8s_config.load_kube_config()
    config_map_name = "mss-deliver"
    namespace = "platform"

    # data = {
    #     "data": {
    #         "time": {
    #             "old": 1234,
    #             "new": 2345
    #         }
    #     }
    # }
    data = {"old2": "123456", "new2": "2345678"}
    config_map_data = {'data': {"time": str(data)}}
    # config_map_data = {'data': {'key.name': 'value12346666', 'key2': 'values111111111111', 'abc': {'name': "czx"}}}
    api_instance = client.CoreV1Api()
    # Use client.V1ConfigMap instead of the python dict
    # object_meta = client.V1ObjectMeta(name=config_map_name, namespace=namespace)
    # body = client.V1ConfigMap(
    #     api_version="v1", kind="ConfigMap", metadata=object_meta, data=config_map_data)
    api_instance.patch_namespaced_config_map(name=config_map_name, namespace=namespace, body=config_map_data)

successful patched,but the result is confused, which with single-quote or double quote:

apiVersion: v1
data:
    time: '{''old2'': ''123456'', ''new2'': ''2345678''}'

anyway, I can't get my expectation

What you expected to happen:
and the dersire result list under.

apiVersion: v1
kind: ConfigMap
metadata:
  name: your-cm-name
data:
  time:
    old: 1234
    new: 2345

How to reproduce it (as minimally and precisely as possible):
copy the code, and run it in a k8s environment.
Anything else we need to know?:

Environment:
kubectl version
Client Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.9", GitCommit:"c1de2d70269039fe55efb98e737d9a29f9155246", GitTreeState:"clean", BuildDate:"2022-07-13T14:26:51Z", GoVersion:"go1.17.11", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.9", GitCommit:"c1de2d70269039fe55efb98e737d9a29f9155246", GitTreeState:"clean", BuildDate:"2022-07-13T14:19:57Z", GoVersion:"go1.17.11", Compiler:"gc", Platform:"linux/amd64"}

  • Kubernetes version (kubectl version):
  • OS (e.g., MacOS 10.13.6): CentOS Linux release 8
  • Python version (python --version) python3.7.9
  • Python client version (pip list | grep kubernetes) 24.2.0
@mqray mqray added the kind/bug Categorizes issue or PR as related to a bug. label Nov 13, 2024
@mqray
Copy link
Author

mqray commented Nov 13, 2024

Incidently, I read this solution config_map.yml and get inspiration.
I notice that # file-like keys, which need add three - --- to express my appeal.
Code as follows:

import logging
from kubernetes import client, config, utils
from kubernetes.client.rest import ApiException

# 设置日志配置
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 加载 Kubernetes 配置
config.load_kube_config()

# 创建 Kubernetes API 客户端
k8s_client = client.ApiClient()

def create_or_update_configmap(namespace, name, old_timestamp, new_timestamp):
    # 准备 ConfigMap 数据
    configmap_data = {
        'apiVersion': 'v1',
        'kind': 'ConfigMap',
        'metadata': {
            'name': name,
            'namespace': namespace
        },
        'data': {
            'time.yml': f'---\ntime:\n  old: "{old_timestamp}"\n  new: "{new_timestamp}"'
        }
    }

    # 尝试创建或更新 ConfigMap
    try:
        # 使用 create_from_dict 方法创建或更新 ConfigMap
        utils.create_from_dict(k8s_client, configmap_data, namespace=namespace)
        logger.info(f"ConfigMap {name} in namespace {namespace} created or updated successfully.")
    except ApiException as e:
        logger.error(f"Failed to create or update ConfigMap {name} in namespace {namespace}: {e}")
        raise

if __name__ == "__main__":
    namespace = "default"
    name = "my-configmap115"
    old_timestamp = 1730781296
    new_timestamp = 1731420745

    create_or_update_configmap(namespace, name, old_timestamp, new_timestamp)

and the result like this:

apiVersion: v1
data:
  time.yml: |-
    ---
    time:
      old: "1730781296"
      new: "1731420745"
kind: ConfigMap
metadata:
  creationTimestamp: "2024-11-12T20:15:32Z"
  name: my-configmap115
  namespace: default
  resourceVersion: "73579909"
  uid: 5df8e893-244d-4250-9d2f-5c380d4d02ba

NOTE that, such approch doesn't the expectation which is update cm by multi-level dict, I just find another way to solve my tsak.

@mqray
Copy link
Author

mqray commented Nov 13, 2024

and, this tripe - --- also work in patch_namespaced_config_map

from kubernetes import client, config as k8s_config
from kubernetes.client.rest import ApiException
import logging
import datetime

k8s_config.load_kube_config()
import os
logging.basicConfig(filename=os.path.join(os.getcwd(),'log.txt'),level=logging.INFO)
def execute_patch_1():
    config_map_name = "mss-deliver"
    namespace = "platform"
    config_map_data = {'data': {'time.yml': f'---\ntime:\n  old: 12345\n  new: 66666666666'}}
    api_instance = client.CoreV1Api()
    # Use client.V1ConfigMap instead of the python dict
    # object_meta = client.V1ObjectMeta(name=config_map_name, namespace=namespace)
    # body = client.V1ConfigMap(
    #     api_version="v1", kind="ConfigMap", metadata=object_meta, data=config_map_data)

    api_instance.patch_namespaced_config_map(name=config_map_name, namespace=namespace, body=config_map_data)

if __name__ == "__main__":
    execute_patch_1()

result are as follows:

apiVersion: v1
data:
  time.yml: |-
    ---
    time:
      old: 12345
      new: 66666666666
kind: ConfigMap

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind/bug Categorizes issue or PR as related to a bug.
Projects
None yet
Development

No branches or pull requests

1 participant