🐶
Kubernetes

kubectl Delete: Revert kubectl apply Changes

By Jan on 02/03/2025

Learn how to revert changes made by "kubectl apply" and restore your Kubernetes resources to a previous state.

kubectl Delete: Revert kubectl apply Changes

Table of Contents

Introduction

There is no single command to directly reverse the effects of kubectl apply -f <file>. Kubernetes operates on a desired state model, aiming to align the cluster's state with your configuration files. Instead of a direct "undo," you'll use different approaches depending on what you want to achieve. Let's explore how to handle various "undo" scenarios in Kubernetes.

Step-by-Step Guide

There is no direct "reverse" for kubectl apply -f <file>. Kubernetes aims to converge the desired state (your config) with the actual state (the cluster).

Here's how to handle different "undo" scenarios:

  1. Removing resources:

    • To delete resources defined in a file, use:
      kubectl delete -f <file>
    • This removes the resources, effectively undoing the apply.
  2. Rolling back deployments:

    • If you want to revert to a previous deployment version:
      kubectl rollout undo deployment/<deployment-name>
    • You can specify a specific revision:
      kubectl rollout undo deployment/<deployment-name> --to-revision=3 
  3. Uninstalling complex applications:

    • For applications installed via Helm or other package managers, use their respective uninstall mechanisms.
  4. No inverse for individual resources:

    • kubectl apply doesn't track history for individual resource changes.
    • To "undo," you need to modify the configuration file to the desired state and re-apply it.

Important Considerations:

  • Order of deletion: When deleting resources, consider dependencies. Deleting in reverse order of creation often helps avoid issues.
  • State, not commands: Kubernetes focuses on the desired state. Think about the end state you want, not just reversing commands.
  • Backups: Always have backups or a rollback plan, especially for production environments.

Code Example

This document provides examples of how to undo kubectl apply actions in various scenarios. It covers removing resources defined in a YAML file, rolling back deployments to previous revisions, uninstalling Helm charts, and addressing the lack of a direct undo for individual resource changes like scaling. The document emphasizes the importance of careful deployment planning and having a rollback strategy.

This example demonstrates different "undo" scenarios for kubectl apply.

Scenario: You have a file named deployment.yaml that defines a Deployment and a Service:

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app
        image: nginx:latest
---
apiVersion: v1
kind: Service
metadata:
  name: my-app-service
spec:
  selector:
    app: my-app
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

1. Removing Resources:

# Apply the resources
kubectl apply -f deployment.yaml

# Delete the resources defined in the file
kubectl delete -f deployment.yaml 

2. Rolling Back a Deployment:

# Assume you've updated the deployment.yaml and applied it multiple times.

# Roll back to the previous deployment revision
kubectl rollout undo deployment/my-app

# Roll back to a specific revision (e.g., revision 3)
kubectl rollout undo deployment/my-app --to-revision=3 

3. Uninstalling a Helm Chart (Example):

# Assuming you installed an app called "my-chart" using Helm

# Uninstall the Helm chart
helm uninstall my-chart

4. No Inverse for Individual Resource Changes:

# Let's say you manually scaled the deployment using:
kubectl scale deployment my-app --replicas=5

# There's no direct "undo" for this specific command. 
# To revert, modify the replicas count in deployment.yaml back to 3 and re-apply:

# Edit deployment.yaml and set replicas: 3

# Re-apply the configuration
kubectl apply -f deployment.yaml 

Important: This is a simplified example. Real-world scenarios might involve more complex resources and dependencies. Always plan your deployments carefully and have a rollback strategy in place.

Additional Notes

  • Idempotency: While there's no direct reverse, kubectl apply is idempotent. Reapplying the same configuration multiple times won't have additional side effects beyond reaching the desired state.
  • Resource Tracking: Consider using tools like kubectl diff -f <file> before applying changes. This shows you a preview of what will be added, modified, or deleted.
  • GitOps: For managing Kubernetes configurations and rollbacks more effectively, explore GitOps practices. Tools like ArgoCD or FluxCD automate deployments and rollbacks based on Git commits.
  • Dry-Run: Before applying potentially destructive changes (like deletions), use kubectl delete -f <file> --dry-run=client or --dry-run=server to simulate the operation without actually deleting anything.
  • Namespaces: If you applied resources to a specific namespace, ensure you include the -n <namespace> flag with kubectl delete to remove them from the correct namespace.
  • Custom Resource Definitions (CRDs): Uninstalling applications that involve CRDs might require additional steps to remove the CRDs themselves, as they are cluster-level resources.
  • StatefulSets: Rolling back StatefulSets requires more caution than Deployments due to potential data persistence concerns. Consult the Kubernetes documentation for specific guidance.
  • Understanding the Desired State: The key takeaway is to focus on defining the desired state in your configuration files. Kubernetes will then work towards making the actual cluster state match your desired configuration.

Summary

Scenario Solution Notes
Remove resources defined in a file kubectl delete -f <file> Effectively undoes the apply command.
Rollback a deployment kubectl rollout undo deployment/<deployment-name>
kubectl rollout undo deployment/<deployment-name> --to-revision=3
Reverts to a previous deployment version. Can specify a specific revision.
Uninstall complex applications (Helm, etc.) Use the package manager's uninstall mechanism.
Undo changes to individual resources No direct inverse. Modify the configuration file to the desired state and re-apply with kubectl apply -f <file>. kubectl apply doesn't track individual resource change history.

Key Points:

  • Dependencies: Delete resources in reverse order of creation to avoid issues.
  • Desired State: Focus on the desired end state, not just reversing commands.
  • Backups: Always have backups and a rollback plan, especially in production.

Conclusion

In conclusion, Kubernetes doesn't offer a single "undo" command for kubectl apply -f <file>. Its declarative approach focuses on achieving the desired state outlined in your configuration files. To reverse changes, you'll need to adopt different strategies based on the specific scenario: deleting resources with kubectl delete -f <file>, rolling back deployments to previous versions, or leveraging package managers' uninstall mechanisms. Remember that understanding resource dependencies, focusing on the end state, and having backups are crucial for successful rollbacks and configuration management in Kubernetes. By mastering these concepts and techniques, you can confidently manage your applications and navigate the intricacies of state reconciliation in Kubernetes.

References

  • Feature request: Reverse order for deleting resources · Issue #2138 ... Feature request: Reverse order for deleting resources · Issue #2138 ... | Is there something like kustomize build --reverse . | kubectl delete -f - as oposite to kustomize build . | kubectl apply -f - ? Would be nice to have reverse order for proper deleting. Deployments...
  • kubernetes - Unapply a config that was applied with apply -f - Stack ... kubernetes - Unapply a config that was applied with apply -f - Stack ... | Sep 13, 2019 ... I have applied a config file like this kubectl apply -f deploy/mysql.yml How can I unapply this specific config?
  • How to Rollback Your Kubernetes Deployment with Kubectl How to Rollback Your Kubernetes Deployment with Kubectl | Learn how to rollback a Kubernetes deployment to a previous version using kubectl commands. Follow our guide to ensure stability in your cluster.
  • kubectl rollout undo | Kubernetes kubectl rollout undo | Kubernetes | Synopsis Roll back to a previous rollout. kubectl rollout undo (TYPE NAME | TYPE/NAME) [flags] Examples # Roll back to the previous deployment kubectl rollout undo deployment/abc # Roll back to daemonset revision 3 kubectl rollout undo daemonset/abc --to-revision=3 # Roll back to the previous deployment with dry-run kubectl rollout undo --dry-run=server deployment/abc Options --allow-missing-template-keys     Default: true If true, ignore any errors in templates when a field or map key is missing in the template.
  • What is the reverse of "kubectl apply"? What is the reverse of "kubectl apply"? | Aug 18, 2022 ... I was playing around in minikube and installed the wrong version of istio. I ran: kubectl apply -f install/kubernetes/istio-demo-auth.yaml
  • kubectl apply | Kubernetes kubectl apply | Kubernetes | Synopsis Apply a configuration to a resource by file name or stdin. The resource name must be specified. This resource will be created if it doesn't exist yet. To use 'apply', always create the resource initially with either 'apply' or 'create --save-config'. JSON and YAML formats are accepted. Alpha Disclaimer: the --prune functionality is not yet complete. Do not use unless you are aware of what the current state is.
  • How do you rollback deployments in Kubernetes? How do you rollback deployments in Kubernetes? | When you introduce a change that breaks production, you should have a plan to roll back that change. Kubernetes and kubectl offer a simple mechanism to roll back changes.
  • Accessing Clusters | Kubernetes Accessing Clusters | Kubernetes | This topic discusses multiple ways to interact with clusters. Accessing for the first time with kubectl When accessing the Kubernetes API for the first time, we suggest using the Kubernetes CLI, kubectl. To access a cluster, you need to know the location of the cluster and have credentials to access it. Typically, this is automatically set-up when you work through a Getting started guide, or someone else set up the cluster and provided you with credentials and a location.
  • Traefik Getting Started With Kubernetes - Traefik Traefik Getting Started With Kubernetes - Traefik | The objective is to learn how to run an application behind a Traefik reverse proxy in Kubernetes. ... kubectl apply -f 03-whoami.yml \ -f 03-whoami-services.yml \ ...

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait