【问题标题】:Kubernetes - check if resources defined in YAML file existKubernetes - 检查 YAML 文件中定义的资源是否存在
【发布时间】:2021-11-03 15:19:58
【问题描述】:

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

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

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

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

documentation,我发现:

将集群的当前状态与应用清单时集群所处的状态进行比较。

kubectl diff -f ./my-manifest.yaml

但我发现很难解析它返回的输出。有没有更好的选择?

【问题讨论】:

    标签: bash kubernetes kubectl


    【解决方案1】:

    确定集群中是否已经存在与清单文件中描述的完全相同的对象。您可以使用kubectl diff 命令的返回码。

    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 环境变量可用于选择您的 自己的差异命令。用户也可以使用带参数的外部命令,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      相关资源
      最近更新 更多