<p>I'm trying to delete Kubernetes evicted pods which are older than 30 days from all namespaces, but the command throws an error :</p>
<pre><code>Error from server(NotFound): pods (xxxxxxxxxxxxx) not found
</code></pre>
<p>Command:</p>
<pre><code>kubectl delete pod $(kubectl get pods --all-namespaces  | grep Evicted | sed 's#d$##' | awk '$6 &gt; 30 {print $2}')&quot;
</code></pre>
<p>Any ideas?</p>

doksha
<p>This assumes the GNU coreutils version of <code>date</code> and a bourne-like shell:</p>
<p>One-liner:</p>
<pre class="lang-bash prettyprint-override"><code>onemonthago=$(date -u -d '-1 month' +&quot;%FT%TZ&quot;); kubectl get pod --field-selector='status.phase=Failed' -o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,STATUS:.status.reason,STARTTIME:.status.startTime -A | while read ns pod status starttime; do if [ &quot;$status&quot; = &quot;Evicted&quot; ]; then if [ &quot;$starttime&quot; \&gt; &quot;$onemonthago&quot; ]; then kubectl -n $ns delete pod $pod --wait=false; fi; fi; done
</code></pre>
<p>More readable formatting:</p>
<pre class="lang-bash prettyprint-override"><code>onemonthago=$(date -u -d '-1 month' +&quot;%FT%TZ&quot;); 
kubectl get pod --field-selector='status.phase=Failed' -o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,STATUS:.status.reason,STARTTIME:.status.startTime -A | while read ns pod status starttime; do 
    if [ &quot;$status&quot; = &quot;Evicted&quot; ]; then 
        if [ &quot;$starttime&quot; \&gt; &quot;$onemonthago&quot; ]; then 
            kubectl -n $ns delete pod $pod --wait=false; 
        fi; 
    fi; 
done
</code></pre>
<p>The details:
<code>onemonthago=$(date -u -d '-1 month' +&quot;%FT%TZ&quot;);</code> gets the cutoff time in the same format as what kubectl returns and stores it in a shell variable.</p>
<p>The kubectl then gets all the failed pods and outputs the columns that we need for further steps.</p>
<p>It then gets piped to a while loop that reads the fields into shell variables.</p>
<p>The <code>if</code> statements then check whether the pod was evicted or is failed for another reason (The <code>status.reason</code> field is not supported for <code>--field-selector</code>) and that it is older than a month. If it matches that criteria, it deletes it.</p>
<p>(It is likely possible to optimise it to gather a list of all pods in a namespace and pass that to the minimum number of kubectls using xargs in one go) (Both checks can be combined, either in the shell or in AWK as well) (Replacing the entire while with an elaborate AWK script would likely yield the best perfomance (collecting a list of pos to delete per namespace and running / outputting the delete command from the <code>END</code> pattern)</p>
