Kubectl Delete All Resources In Namespace

6 min read

Managing Kubernetes clusters often requires cleaning up environments, tearing down test deployments, or resetting namespaces to a pristine state. One of the most common operational tasks is removing every workload, configuration, and storage object within a specific namespace without deleting the namespace itself. The command kubectl delete all --all -n <namespace> is the standard starting point for this, but experienced engineers know it carries significant caveats. Understanding exactly what this command touches—and what it leaves behind—is critical for maintaining cluster hygiene and avoiding accidental data loss.

Understanding the Scope of kubectl delete all

The phrase "delete all" is slightly deceptive. Also, in Kubernetes, all is a shortcut resource group, not a literal instruction to delete every API object in existence. When you run kubectl api-resources --verbs=delete --namespaced -o name | grep -v "all", you see dozens of resource types Worth keeping that in mind. Took long enough..

  • Workloads: Pods, Deployments, ReplicaSets, StatefulSets, DaemonSets, Jobs, CronJobs, ReplicationControllers.
  • Networking & Load Balancing: Services, Ingresses.
  • Configuration: ConfigMaps, Secrets.
  • Storage: PersistentVolumeClaims (PVCs).

Still, it notably excludes several critical resource types that live inside a namespace. If you rely solely on kubectl delete all --all, you will leave behind:

  • Custom Resource Definitions (CRDs) instances: Any operator-managed resources (e.g., Database, KafkaCluster, Certificate).
  • Role-Based Access Control (RBAC): Roles and RoleBindings specific to that namespace.
  • Service Accounts: Identities used by pods to talk to the API server.
  • Resource Quotas & Limit Ranges: Policies governing resource consumption.
  • Network Policies: Firewall rules for pod communication.
  • Persistent Volumes (PVs): While PVCs are deleted, the underlying PV (cluster-scoped) may remain bound or released depending on the reclaimPolicy.

The Standard Command Syntax

To delete the standard set of resources within a specific namespace, the syntax is straightforward:

kubectl delete all --all -n 

Breakdown of flags:

  • all: The resource group shortcut.
  • --all: Instructs kubectl to select every resource of the types included in the all group. Without this flag, you would need to specify resource names individually.
  • -n <namespace-name>: Targets the specific namespace. Always double-check this flag. Omitting it targets the default namespace or your current context's namespace, which can be catastrophic in production.

Adding Grace Periods and Force Deletion

By default, Kubernetes sends a SIGTERM signal to pods and waits for the terminationGracePeriodSeconds (default 30s) before sending SIGKILL. For rapid cleanup in non-production environments, you can accelerate this:

kubectl delete all --all -n  --grace-period=0 --force
  • --grace-period=0: Skips the graceful termination wait.
  • --force: Required when grace period is 0; immediately removes the object from etcd without waiting for confirmation from the Kubelet that the process has stopped.

Warning: Using --force --grace-period=0 on StatefulSets or Pods using PersistentVolumes can lead to data corruption or "zombie" pods if the underlying storage is not properly unmounted. Avoid this in production environments running databases or stateful applications.

Handling the "Leftovers": A Complete Cleanup Strategy

Because kubectl delete all leaves gaps, a dependable cleanup script or manual workflow must address the excluded resources. The most reliable method is to delete the namespace itself and recreate it, but organizational policies often forbid deleting the namespace object (due to RBAC bindings, quota history, or GitOps controllers that manage the namespace lifecycle) Easy to understand, harder to ignore..

If you cannot delete the namespace, use the following comprehensive approach.

1. Delete All Namespaced Resources via Label Selector

You can target every namespaced resource type known to the API server using a label selector that matches everything (effectively no label filter) combined with the --all-namespaces logic restricted to one namespace And that's really what it comes down to..

# Get all namespaced resource types that support deletion
kubectl api-resources --verbs=delete --namespaced -o name | \
xargs -I {} kubectl delete {} --all -n  --ignore-not-found=true

Explanation:

  • kubectl api-resources --verbs=delete --namespaced -o name: Lists every deletable, namespaced resource (including CRDs).
  • xargs -I {} kubectl delete {} --all ...: Iterates through that list and issues a delete command for each type.
  • --ignore-not-found=true: Prevents the script from exiting with an error if a resource type exists in the API but has zero instances in that namespace.

This is the "nuclear option" for a namespace. It cleans up Roles, RoleBindings, ServiceAccounts, NetworkPolicies, CR instances, and everything else Simple as that..

2. Handling Finalizers and Stuck Resources

Sometimes resources hang in Terminating state indefinitely. This usually happens because a Finalizer blocks deletion (common with external cloud controllers, storage drivers, or operators like Cert-Manager or Istio).

To force removal of a stuck resource, you must patch the finalizer list to be empty:

# Example: Force delete a stuck PVC
kubectl patch pvc  -n  -p '{"metadata":{"finalizers":null}}' --type=merge

# Then delete it
kubectl delete pvc  -n  --grace-period=0 --force

Apply this pattern to any resource type (pod, deployment, statefulset, crd-instance) that refuses to disappear Worth knowing..

3. Persistent Volume Claims (PVCs) and Data Retention

Deleting a PVC triggers the deletion of the bound Persistent Volume (PV) only if the PV's reclaimPolicy is set to Delete. If the policy is Retain, the PV remains in a Released state, and the data on the underlying storage (EBS disk, NFS share, Ceph RBD) persists.

  • To save data: Ensure reclaimPolicy: Retain before deleting the PVC. You can manually reclaim the PV later.
  • To wipe data: Ensure reclaimPolicy: Delete (often the default for dynamic provisioning via StorageClasses). Deleting the PVC will trigger the cloud provider CSI driver to destroy the disk.

Check your StorageClass:

kubectl get storageclass -o yaml | grep -A 5 reclaimPolicy

Automation: A Safe Cleanup Script

For repeatable operations (e.g.Because of that, , CI/CD pipeline teardown, end-of-day dev cluster reset), wrap the logic in a script. This example includes safety checks.

#!/bin/bash
# cleanup-namespace.sh
# Usage: ./cleanup-namespace.sh 

set -euo pipefail

NAMESPACE=${1:-}

if [[ -z "$NAMESPACE" ]]; then
  echo "Error: Namespace argument required."
  echo "Usage: $0 "
  exit 1
fi

# Safety check: Prevent accidental deletion of system namespaces
PROTECTED=("kube-system" "kube-public" "kube-node-lease" "default" "monitoring" "ingress-nginx")
for ns in "${PROTECTED[@]}"; do
  if [[ "$NAMESPACE" == "$

The check therefore aborts the run if the caller tries to wipe a protected namespace:

```bash
if [[ " ${PROTECTED[*]} " == *"$NAMESPACE"* ]]; then
  echo "Error: $NAMESPACE is a protected namespace and cannot be deleted."
  exit 1
fi

4. Iterating Over All Namespaced Resources

A single kubectl delete command can target a whole class of objects, but it is often clearer (and safer) to delete each kind explicitly. The following loop pulls every namespaced resource, strips the metadata block that contains finalizers, and then forces removal:

# Collect all namespaced objects (excluding the namespace itself)
resources=(
  $(kubectl get all -n "$NAMESPACE" -o name)
  $(kubectl get configmap -n "$NAMESPACE" -o name)
  $(kubectl get secret -n "$NAMESPACE" -o name)
  $(kubectl get pvc -n "$NAMESPACE" -o name)
  $(kubectl get cm -n "$NAMESPACE" -o name)
  $(kubectl get crd -n "$NAMESPACE" -o name)   # CRDs are cluster‑scoped; we handle them later
)

# Delete each resource with zero grace period and force
for res in "${resources[@]}"; do
  # Extract kind and name
  kind=$(echo "$res" | cut -d'/' -f1)
  name=$(echo "$res" | cut -d'/' -f2)

  # Special handling for PVCs – ensure the PV reclaim policy permits deletion
  if [[ "$kind" == "pvc" ]]; then
    # Fetch the reclaim policy of the bound PV
    pv=$(kubectl get pvc "$name" -n "$NAMESPACE" -o jsonpath='{.spec.Worth adding: volumeName}')
    policy=$(kubectl get pv "$pv" -o jsonpath='{. spec.reclaimPolicy}')
    if [[ "$policy" == "Retain" ]]; then
      echo "Skipping PVC $name (PV $pv is Retain).

  # Patch out finalizers if present (this works for any resource that supports them)
  if
What Just Dropped

New Picks

See Where It Goes

In the Same Vein

Thank you for reading about Kubectl Delete All Resources In Namespace. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home