首页 > 解决方案 > 获取停留在终止状态超过 10 分钟的 Pod 列表,并在 Ansible 中将其删除

问题描述

我想使用 Ansible 获取停留在终止状态超过 10 分钟的 pod 列表。目前我正在编写一个脚本来做到这一点,但我觉得必须有更好的方法来做同样的事情。我计划用以下代码片段中的一个替换describepod 命令。delete

# Command used to delete :  kubectl delete pod $PodName -n {{item}} --force --grace-period=0;
- name: get list of pods and remove the not ready ones
  shell: |
    noOfPODs=`kubectl get pods -n {{item}} | egrep "0/1|Terminating" | wc -l`;
    if [ $noOfPODs -gt 0 ];
      then
        kubectl get pods -n {{item}} | egrep "0/1|Terminating"   > {{ not_ready_pods_file }} ;
        while read line; do
          PodName=$(echo $line | awk {'print $1'})
          PodTime=$(kubectl describe pod $PodName -n {{item}} | grep Terminating | awk {'print $4'} | tr -d 'mhd)')
          if [ -z $PodTime ];
          then
            PodTime=$(echo $line | awk {'print $5'} | tr -d 'mhd')
          fi
          echo "$PodTime is PodTime"
          if [[ $PodTime == *s ]] ;
          then
            echo "PodTime in seconds"
          else
            if [ $PodTime -gt 10 ];
            then
              echo "\n$PodName" >> {{ deleted_pods_file }};
              kubectl delete pod $PodName -n {{item}} --force --grace-period=0;
            fi
          fi
        done < {{ not_ready_pods_file }}
    else
      echo 'No Pods in NOT READY or Terminating state';
    fi
  environment:
    KUBECONFIG: "./_kubeconfig/{{ env }}/kubeconfig"
  loop:
    - somenamespace
- name: Search for all running pods
  k8s_info:
    kind: Pod
    field_selectors:
      - status.phase=Running
    kubeconfig: "./_kubeconfig/{{ env }}/kubeconfig"

有没有更好的方法来做到这一点?喜欢在 Prometheus 等中做。Shell 脚本可以工作,但似乎不是正确的方法。

标签: kubernetesansibleprometheus

解决方案


您可以利用go-template这一点并做类似的事情:

kubectl get pods --all-namespaces -o go-template --template '{{range .items}}{{if eq (.status.phase) ("Terminating")}}{{if gt (.status.startTime) ("2020-07-03T04:18:02Z")}}{{.metadata.name}}{{"\n"}}{{end}}{{end}}{{end}}'

{{if gt (.status.startTime) ("2020-07-03T04:18:02Z")}}应该换成你自己的时间条件。


推荐阅读