在 Kubernetes 中使用完整的声明式方法

Using full Declarative approach in Kubernetes

我们可以使用声明式方法使用 kubectl apply -f 创建和更新 kubernetes 资源,我们如何做同样的事情来回收不再需要的资源。

我用过 kubectl delete ,但这看起来像是命令式的,有时我们需要按正确的顺序删除内容。

有没有一种方法可以始终使用 kubectl apply 并自行确定要保留哪些资源以及删除哪些资源。就像 Terraform.

或者我们应该得出结论,目前声明式方法仅适用于资源创建和更新。

用例:

例如,我们决定不向最终用户提供 K8S API,而是为他们提供一个存储库,用于保存和更新他们的 yaml 文件,机器人可以在每次更新时将其应用于集群拉取请求已合并。所以我们也需要这个声明性的删除,这样我们就不必在用户之后清理东西。 Terraform provider 可能是解决方案,但在那种情况下,事情将锁定到 terraform,用户将需要再学习一种工具,而不是使用本机 k8s 格式。

原来他们已经添加了一种声明性方法来修剪 yaml 清单中不再存在的资源:

kubectl apply -f <directory/> --prune -l your=label

虽然有太多的注意事项。

As an alternative to kubectl delete, you can use kubectl apply to identify objects to be deleted after their configuration files have been removed from the directory. Apply with --prune queries the API server for all objects matching a set of labels, and attempts to match the returned live object configurations against the object configuration files. If an object matches the query, and it does not have a configuration file in the directory, and it has a last-applied-configuration annotation, it is deleted.