I feel like I have a terrible knowledge gap when it comes to managing the resource states within Kubernetes.

Suppose I have 2 deployments in my cluster, foo1 and foo2. They are both defined in separate yaml files, foo1.yaml and foo2.yaml that are both inside a my-dir directory and have been applied with kubectl apply -f my-dir/

Now I want to make a third deployment, but also delete my second deployment. I know that I can do this in 2 steps:

  • Make another foo3.yaml file inside the directory and then do kubectl apply -f my-dir/foo3.yaml
  • Run kubectl delete -f my-dir/foo2.yaml to get rid of the second deployment.

My question is, can I do this in one shot by keeping the "desired state" in my directory. i.e. Is there any way that I can delete foo2.yaml, create a new foo3.yaml and then just do kubectl apply -f my-dir/ to let kubernetes handle the deletion of the removed resource file as well? What am I missing here?

1 Answer 1


The professional solution is something like fluxcd. This will automatically "apply" any .yaml files that you commit to your git repo, and also automatically remove those resources if it tracks that they have been deleted from the repo.

The problem with what you are asking for, is that kubernetes needs a way of knowing which resources you want it to delete. (For example, you may be using a shared cluster, and not want to inadvertently delete other applications and system pods, even if they are not explicitly mentioned in your private local working directory.) That said, if you have diligently labelled the specific resources you want to manage, then the feature does exist: use the --prune argument to kubectl apply as described in the docs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.