<p>I am creating a bash script to automate certain actions in my cluster. One of the commands is: <code>kubectl delete -f example.yaml</code>.</p>
<p>The problem is that when the resources defined in the YAML do not exist, the following error is printed:</p>
<pre><code>Error from server (NotFound): error when deleting &quot;example.yaml&quot;: deployments.apps &quot;my_app&quot; not found
</code></pre>
<p>I am looking to add an additional step that first checks whether a set of resources defined in a YAML file exist in the cluster. Is there a command that would allow me to do so?</p>
<p>From the <a href="https://kubernetes.io/docs/reference/kubectl/cheatsheet/" rel="noreferrer">documentation</a>, I found:</p>
<blockquote>
<h1>Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied.</h1>
<p>kubectl diff -f ./my-manifest.yaml</p>
</blockquote>
<p>but I find it difficult to parse the output that it returns. Is there a better alternative?</p>

sqlquestionasker
<p>To find out if the same object is already present in the cluster as exactly described in the manifest file. you can use the return code of the <code>kubectl diff</code> command.</p>
<pre><code>Exit status:
 0 No differences were found.
 1 Differences were found. 
 &gt;1 Kubectl or diff failed with an error.
</code></pre>
<p>Example:</p>
<pre><code>kubectl diff -f crazy.yml &amp;&gt;/dev/null
rc=$?
if [ $rc -eq 0 ];then
  echo &quot;Exact Object is already installed on the cluster&quot;
elif [ $rc -eq 1 ];then
  echo &quot;Exact object is not installed, either its not installed or different from the manifest file&quot;
else
  echo &quot;Unable to determine the difference&quot;
fi
</code></pre>
<p>Alternatively, if you want to really parse the output,  you may use the following env variable to print the diff output in desired format:</p>
<blockquote>
<p>KUBECTL_EXTERNAL_DIFF environment variable can be used to select your
own diff command. Users can use external commands with params too,</p>
</blockquote>
