gpt4 book ai didi

python - 通过 Python 替换 Kubernetes 中的作业

转载 作者:行者123 更新时间:2023-12-05 05:31:43 25 4
gpt4 key购买 nike

我有以下代码:

 kubectl get job <JOB-NAME> -o json | jq 'del(.spec.selector)' | jq 'del(.spec.template.metadata.labels)' | kubectl replace --force -f -

用自身替换现有的 Kubernetes 作业。是否可以使用 Python Kubernetes API 执行此操作?

这是我现在要做的:

import kubernetes as kubernetes
from kubernetes import client, config

# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()

configuration = kubernetes.client.Configuration()
name = "job-1"
namespace = "default"

v1 = client.CoreV1Api()

# Grab the exact name of the pod based on the job
metabase_create_readonly_user_name = ''
pods = v1.list_namespaced_pod(namespace, label_selector='job-name={}'.format(name), watch=False)
for pod in pods.items:
job_name = pod.metadata.name


# THIS DOES NOT WORK!
v1.replace_namespaced_pod(job_name, namespace)

但是,replace_namespaced_pod 需要一个 body 作为参数传入,所以我不确定该给它什么。有没有办法获取现有作业的确切主体并将其传递到此处?

最佳答案

kubectl replace 命令有一个 --force 选项,它实际上不使用替换,即 PUT,API 端点。它使用提供的规范强制删除 (DELETE) 然后重新创建 (POST) 资源。

根据kubernetes python client docs :

BatchV1Api( Api ) 类下,有 3 个方法:

read_namespaced_jobdelete_namespaced_jobcreate_namespaced_job

所以下面的代码片段就足够了:

from kubernetes import client, config

config.load_kube_config()

batch_v1 = client.BatchV1Api()
...
v1_job = batch_v1.read_namespaced_job(name, namespace)
# some processing to v1_job
v1_job.metadata.resource_version = None
v1_job.metadata.uid = None
# as in your example
v1_job.spec.selector = None
v1_job.spec.template.metadata.labels = None
...
# forcibly deletes
batch_v1.delete_namespaced_job(name, namespace)
# recreates
batch_v1.create_namespaced_job(namespace, v1_job)

关于python - 通过 Python 替换 Kubernetes 中的作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74307365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com