Using full Declarative approach in Kubernetes

10/15/2018

We can use a declarative approach for creating and updating kubernetes resources using kubectl apply -f , how can we do the same for recyclying the resources that are no longer needed.

I have used kubectl delete , but that looks like imperative , and sometimes we will need to delete things in proper order.

Is there a way to always use kubectl apply and it figures out itself which resources to keep and which to delete. Just like in Terraform.

Or we should conclude that currently the declarative approach works for resource creation and update only.

Use case:

For example , we have decided not to provide the K8S API to end users and instead provide them a repository where they keep and update thier yaml files that a bot can apply to the cluster on each update when the pull request is merged. So we need this declarative delete as well so that we don't have to clean up things after users. Terraform provider maybe the solution but in that case things will lock to terraform and users will need to learn one more tool instead of using the native k8s format.

-- Ijaz Ahmad Khan
infrastructure-as-code
kubernetes

1 Answer

10/15/2018

Truns out that they have added a declarative approach for pruning the resources that are no longer present in the yaml manifests:

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

With too many cautions though.

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.

-- Ijaz Ahmad Khan
Source: StackOverflow