gpt4 book ai didi

python - 从 Python 中删除现有 Pod 的简单方法

转载 作者:行者123 更新时间:2023-12-02 11:34:52 25 4
gpt4 key购买 nike

我有用 pytest 编写的端到端测试,在命名空间中的 Kubernetes 集群上运行 foo .现在我想在测试中添加简单的混沌工程来检查我的服务的弹性。为此,我只需要删除 foo 中的特定 Pod -- 由于k8s重启了对应的服务,模拟服务暂时不可达。
使用 Python 删除当前命名空间中特定 pod 的简单方法是什么?

到目前为止我尝试过的:
由于我在 https://github.com/kubernetes-client/python/tree/master/examples 中没有找到合适的例子,但是使用 pods 的看起来很复杂,
我查看了 kubetest ,看起来非常简单优雅。
我想使用 kube固定装置,然后做这样的事情:

pods = kube.get_pods()
for pod in pods:
if can_be_temporarily_unreachable(pod):
kube.delete(pod)
我想用参数 --in-cluster 调用 pytest会告诉 kubetest使用当前的集群设置而不是创建新的 K8s 资源。
然而, kubetest想要为每个使用 kube 的测试用例创建一个新的命名空间固定装置,这是我不想要的。
有没有办法告诉 kubetest不是创建新的命名空间而是在当前命名空间中执行所有操作?
虽然 kubetest否则看起来非常简单和优雅,我也很高兴使用另一种解决方案。
一个需要很少时间和维护并且不会使(阅读)测试复杂化的简单解决方案会很棒。

最佳答案

您可以使用 delete_namespaced_pod (来自 CoreV1Api )删除命名空间中的特定 pod。
下面是一个例子:

from kubernetes import client, config
from kubernetes.client.rest import ApiException
config.load_incluster_config() # or config.load_kube_config()

configuration = client.Configuration()

with client.ApiClient(configuration) as api_client:
api_instance = client.CoreV1Api(api_client)

namespace = 'kube-system' # str | see @Max Lobur's answer on how to get this
name = 'kindnet-mpkvf' # str | Pod name, e.g. via api_instance.list_namespaced_pod(namespace)

try:
api_response = api_instance.delete_namespaced_pod(name, namespace)
print(api_response)
except ApiException as e:
print("Exception when calling CoreV1Api->delete_namespaced_pod: %s\n" % e)

关于python - 从 Python 中删除现有 Pod 的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64221992/

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