<p>I want to get the list of pods stuck in terminating state for more than 10 minutes using Ansible. Currently I am writing a script to do that but I feel there has to be a better way of doing the same. I plan to replace the <code>describe</code> pod command with <code>delete</code> one in the following code snippet.</p>
<pre class="lang-yaml prettyprint-override"><code># 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 &quot;0/1|Terminating&quot; | wc -l`;
    if [ $noOfPODs -gt 0 ];
      then
        kubectl get pods -n {{item}} | egrep &quot;0/1|Terminating&quot;   &gt; {{ 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 &quot;$PodTime is PodTime&quot;
          if [[ $PodTime == *s ]] ;
          then
            echo &quot;PodTime in seconds&quot;
          else
            if [ $PodTime -gt 10 ];
            then
              echo &quot;\n$PodName&quot; &gt;&gt; {{ deleted_pods_file }};
              kubectl delete pod $PodName -n {{item}} --force --grace-period=0;
            fi
          fi
        done &lt; {{ not_ready_pods_file }}
    else
      echo 'No Pods in NOT READY or Terminating state';
    fi
  environment:
    KUBECONFIG: &quot;./_kubeconfig/{{ env }}/kubeconfig&quot;
  loop:
    - somenamespace
</code></pre>
<ul>
<li>I tried using <code>k8s_info</code> in ansible but it gives a huge output which does not have <code>time</code></li>
</ul>
<pre class="lang-yaml prettyprint-override"><code>- name: Search for all running pods
  k8s_info:
    kind: Pod
    field_selectors:
      - status.phase=Running
    kubeconfig: &quot;./_kubeconfig/{{ env }}/kubeconfig&quot;
</code></pre>
<p>Is there any better way of doing this ? like to do in Prometheus etc. Shell script will work but does not seem like the right way.</p>

<p>You could leverage <code>go-template</code> for this and do something similar to:</p>
<pre><code>kubectl get pods --all-namespaces -o go-template --template '{{range .items}}{{if eq (.status.phase) (&quot;Terminating&quot;)}}{{if gt (.status.startTime) (&quot;2020-07-03T04:18:02Z&quot;)}}{{.metadata.name}}{{&quot;\n&quot;}}{{end}}{{end}}{{end}}'
</code></pre>
<p><code>{{if gt (.status.startTime) (&quot;2020-07-03T04:18:02Z&quot;)}}</code> should be replaced by your own time conditions.</p>
