Skip to content
LatchkeyLatchkey home

kubectl delete: Command Reference for CI/CD

Remove resources by name, label, or the manifest you applied.

kubectl delete powers teardown jobs and preview-environment cleanup. This reference lists the flags that control scope and termination timing, plus a CI pattern that scopes deletes to a namespace so a stray --all cannot wipe the wrong place.

Common flags and usage

  • -f <manifest>: delete exactly what a manifest set created
  • -l, --selector: delete every object matching a label
  • --all: delete all objects of a type in the namespace (scope with -n!)
  • --wait=false: return without blocking on graceful termination
  • --grace-period=0 --force: skip graceful termination for a stuck pod
  • --timeout: cap how long delete blocks before failing

Example

shell
# Tear down a per-build preview namespace
kubectl delete namespace ci-${BUILD_ID} --timeout=120s

# Targeted teardown of just this build's objects
kubectl delete -f k8s/ -l build=${BUILD_ID} --wait=true

In CI

Always scope teardown to a dedicated namespace and delete that namespace rather than using --all without -n, which deletes everything in the default namespace. Pass --timeout so a finalizer that hangs a delete fails the step instead of stalling until the job-level timeout.

Using this in CI

A runner has no kubeconfig, no cached context, and no interactive auth. Every kubectl invocation in CI needs the context supplied explicitly, and most confusing CI failures here are the command running against the wrong cluster or no cluster at all.

Terminal
# never rely on the ambient context on a runner
kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" get pods

# confirm what you are actually connected to before mutating anything
kubectl config current-context
kubectl cluster-info

# fail fast instead of hanging on an unreachable API server
kubectl --request-timeout=30s get nodes

Key takeaways

  • Scope teardown to a namespace; --all without -n hits the default namespace.
  • A delete that hangs is usually a finalizer; cap it with --timeout.
  • --grace-period=0 --force is a last resort for known-stuck fixtures only.

Frequently asked questions

kubectl delete: Command Reference for CI/CD?
kubectl delete powers teardown jobs and preview-environment cleanup. This reference lists the flags that control scope and termination timing, plus a CI pattern that scopes deletes to a namespace so a stray --all cannot wipe the wrong place.
In CI?
Always scope teardown to a dedicated namespace and delete that namespace rather than using --all without -n, which deletes everything in the default namespace. Pass --timeout so a finalizer that hangs a delete fails the step instead of stalling until the job-level timeout.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card