获取卡在终止状态超过 10 分钟的 Pod 列表并在 Ansible 中删除它们

cod*_*diz 6 ansible kubernetes prometheus

我想使用 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
Run Code Online (Sandbox Code Playgroud)
  • 我尝试k8s_info在 ansible 中使用,但它提供了一个没有的巨大输出time
- name: Search for all running pods
  k8s_info:
    kind: Pod
    field_selectors:
      - status.phase=Running
    kubeconfig: "./_kubeconfig/{{ env }}/kubeconfig"
Run Code Online (Sandbox Code Playgroud)

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

Ott*_*sky 3

您可以利用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}}'
Run Code Online (Sandbox Code Playgroud)

{{if gt (.status.startTime) ("2020-07-03T04:18:02Z")}}应该根据自己的时间条件来代替。