【问题标题】:Simple way to delete existing pods from Python从 Python 中删除现有 pod 的简单方法
【发布时间】:2021-01-21 02:36:07
【问题描述】:

我有用 pytest 编写的端到端测试,在命名空间 foo 中的 Kubernetes 集群上运行。现在我想在测试中添加简单的混沌工程来检查我的服务的弹性。为此,我只需要删除foo内的特定Pod——由于K8s重启了对应的服务,这就模拟了服务暂时不可达。

用 Python 删除当前命名空间中特定 pod 的简单方法是什么?


到目前为止我所尝试的:

由于我在https://github.com/kubernetes-client/python/tree/master/examples 中没有找到合适的示例,但是使用 pod 的示例看起来很复杂, 我查看了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 在其他方面看起来非常简单和优雅,但我也很乐意使用其他解决方案。 一个简单的解决方案,需要很少的时间和维护,并且不会使(阅读)测试复杂化。

【问题讨论】:

    标签: python kubernetes microservices pytest chaos


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

    【解决方案2】:

    Tibebes 现有答案的延续。 M

    如何找出代码本身运行所在的命名空间?

    有两种方法可以做到这一点:

    1. 使用 Downward API 将 pod 命名空间传递给 pod 环境变量:
    2. 使用您的模板引擎/helm 将环境变量命名空间另外传递给 pod。例子:
               env:
               - name: CURRENT_NAMESPACE
                 value: "{{ .Values.namespace }}"
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-07
      • 2018-05-02
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多