Search code examples
bashkuberneteskubectl

Kubernetes - check if resources defined in YAML file exist


I am creating a bash script to automate certain actions in my cluster. One of the commands is: kubectl delete -f example.yaml.

The problem is that when the resources defined in the YAML do not exist, the following error is printed:

Error from server (NotFound): error when deleting "example.yaml": deployments.apps "my_app" not found

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?

From the documentation, I found:

Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied.

kubectl diff -f ./my-manifest.yaml

but I find it difficult to parse the output that it returns. Is there a better alternative?


Solution

  • 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 kubectl diff command.

    Exit status:
     0 No differences were found.
     1 Differences were found. 
     >1 Kubectl or diff failed with an error.
    

    Example:

    kubectl diff -f crazy.yml &>/dev/null
    rc=$?
    if [ $rc -eq 0 ];then
      echo "Exact Object is already installed on the cluster"
    elif [ $rc -eq 1 ];then
      echo "Exact object is not installed, either its not installed or different from the manifest file"
    else
      echo "Unable to determine the difference"
    fi
    

    Alternatively, if you want to really parse the output, you may use the following env variable to print the diff output in desired format:

    KUBECTL_EXTERNAL_DIFF environment variable can be used to select your own diff command. Users can use external commands with params too,