Kubernetes - 检查 YAML 文件中定义的资源是否存在

Kubernetes - check if resources defined in YAML file exist

我正在创建一个 bash 脚本来自动执行集群中的某些操作。其中一个命令是:kubectl delete -f example.yaml.

问题是当YAML中定义的资源不存在时,打印如下错误:

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

我希望添加一个额外的步骤,首先检查集群中是否存在 YAML 文件中定义的一组资源。是否有允许我这样做的命令?

documentation,我发现:

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

但我发现很难解析它 returns 的输出。有更好的选择吗?

查明同一对象是否已存在于集群中,正如清单文件中所描述的那样。您可以使用 kubectl diff 命令的 return 代码。

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

示例:

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

或者,如果您想真正解析输出,您可以使用以下环境变量以所需格式打印差异输出:

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