<p>I'm testing a trigger i set on my k8s cluster. What it does it that detects if a pod is evicted. So to test I ran</p>
<p><code>kubectl drain &lt;NODENAME&gt; --ignore-daemonsets --force</code></p>
<p>but the evicted pods are just automatically deleted instead of staying in cluster.
Can you guys help me on how can I evict a pod?
I'm using kind to test this locally on my computer.
Actually I want to read the evicted pod yaml after its evicted so that I can build that trigger.</p>

Muhammad Ali Khan
<p>First, to answer the title question: &quot;How to evict pods in kubernetes?&quot; There are a number of additional ways to trigger pod eviction, but two easy ones:</p>
<h3>API Based Eviction</h3>
<p>There is an API you can use to <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.25/#create-eviction-pod-v1-core" rel="nofollow noreferrer">evict a pod manually</a>. To use the API:</p>
<ul>
<li>via curl: <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/api-eviction/" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/scheduling-eviction/api-eviction/</a></li>
<li>with a tool: <a href="https://github.com/rajatjindal/kubectl-evict-pod" rel="nofollow noreferrer">https://github.com/rajatjindal/kubectl-evict-pod</a></li>
</ul>
<h2>Apply a NoExecute Taint</h2>
<p>A <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/#concepts" rel="nofollow noreferrer">NoExecute taint</a> that your pod does not tolerate will cause it to be evicted.</p>
<pre><code>kubectl taint nodes node1 key1=value1:NoExecute
</code></pre>
<p>Now, the text of your question asks a slightly different question: reading the pod resource <em>after</em> a successful eviction. At least in my environment and k8s version, as soon as a pod is evicted, it is deleted by the service account associated with the node it was running on.</p>
<p>In practice, many things can delete pods - including <a href="https://kubernetes.io/docs/concepts/architecture/garbage-collection/" rel="nofollow noreferrer">garbage collectors</a>, so querying a pod after it has been terminated is fraught with potential race conditions.</p>
<p>Instead, I would recommend setting up a programmatic watch for pod events. <code>client-go</code> offers <a href="https://medium.com/codex/explore-client-go-informer-patterns-4415bb5f1fbd" rel="nofollow noreferrer">the Informer pattern</a> to accomplish this with a bit of boilerplate.</p>
<p>Create an informer for Pods, define an <code>UpdateFunc</code> for your event handler, and you will reliably receive pod state changes as they are processed by the API -- which you can then assess to determine if they were evicted.</p>
