kubectl delete: Remove Resources in CI
Delete resources by name, file, or label selector.
kubectl delete removes resources, either by naming them, applying the same manifests used to create them, or matching a selector. In CI it tears down ephemeral preview environments. --ignore-not-found keeps cleanup idempotent so re-runs do not fail.
Common flags
-f file.yaml- delete what a manifest defines-l key=value- delete by label selector--ignore-not-found- exit 0 if the resource is already gone--grace-period=0 --force- force-delete a stuck resource
Example in CI
Tear down a preview namespace idempotently.
shell
kubectl delete namespace pr-${PR_NUMBER} --ignore-not-foundCommon errors in CI
- Error from server (NotFound): ... not found - already deleted; add --ignore-not-found
- namespace ... stuck Terminating - finalizers blocking deletion
- Forbidden: ... is forbidden - RBAC denies delete on the resource
Key takeaways
- Deletes resources by name, file, or selector.
- Use --ignore-not-found to keep cleanup steps idempotent.
- A namespace stuck Terminating usually has lingering finalizers.
Related guides
kubectl create secret: Manage Secrets in CICreate Kubernetes secrets in CI: generic and docker-registry flags, an idempotent example, and the AlreadyExi…
kubectl apply: Deploy Manifests in CIApply Kubernetes manifests declaratively in CI: the flags you use most, a pipeline example, and the apply err…
kubectl wait: Block on Conditions in CIWait for a Kubernetes condition in CI: --for and --timeout flags, a readiness-gate example, and the timeout e…