kubernetes - 获取停留在终止状态超过 10 分钟的 Pod 列表,并在 Ansible 中将其删除
问题描述
我想使用 Ansible 获取停留在终止状态超过 10 分钟的 pod 列表。目前我正在编写一个脚本来做到这一点,但我觉得必须有更好的方法来做同样的事情。我计划用以下代码片段中的一个替换describe
pod 命令。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
- 我尝试
k8s_info
在 ansible 中使用,但它提供了巨大的输出,而没有time
- name: Search for all running pods
k8s_info:
kind: Pod
field_selectors:
- status.phase=Running
kubeconfig: "./_kubeconfig/{{ env }}/kubeconfig"
有没有更好的方法来做到这一点?喜欢在 Prometheus 等中做。Shell 脚本可以工作,但似乎不是正确的方法。
解决方案
您可以利用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")}}
应该换成你自己的时间条件。
推荐阅读
- php - 在 PHP 中执行可恢复上传 - Google Cloud Storage
- angular - 如何接收通过 HttpParams 发送的参数
- oracle - PLS-00320:此表达式类型的声明不完整或格式错误 - ORACLE PRIVILEGES ISSUE
- python - 随着时间的推移,如何增加解释变量对 Y 的影响?
- wordpress - WordPress Gutenberg RichText 不显示 HTML
- java - mysql 连接器/J 8 更改 - 版本 8.0.12
- clojure - 将矢量转换为地图
- c# - 处理 WebSocket 服务器端
- laravel - Laravel 5中没有标签的重定向
- c# - 如何将方法1封装到方法2规范流?