A plugin for kubectl that matches a special annotation in applied YAML with the current kubectl context, preventing you from accidentally applying files meant for one context to another.
- Make sure you have uv installed.
- Put
kubectl-safe_apply
andkubectl-safe_delete
somewhere on your path - Make them executable (
chmod +x /path/to/kubectl-safe_*
)
- Put the following somewhere on your path:
kubectl-safe_apply
kubectl-safe_apply.cmd
kubectl-safe_delete
kubectl-safe_delete.cmd
-
Try applying a k8s YAML file using
safe-apply
:$ kubectl safe-apply -f my-file.yaml Attempting to apply Pod 'my-pod' without a safe-apply/require-context annotation. Aborting.
-
Now add the annotation specifying which context is required:
apiVersion: v1 kind: Pod metadata: annotations: safe-apply/require-context: my-production-cluster name: my-pod ...
-
Try safe-applying again:
$ kubectl safe-apply -f my-file.yaml Attempting to apply to incorrect context for Pod 'my-pod'. Current: default, required: my-production-cluster
-
Switch to the correct context (using something like
kubectx
) and try again:$ kubectx my-production-cluster $ kubectl safe-apply -f my-file.yaml pod/my-pod configured
-
All arguments to
kubectl safe-apply
are passed through as-is tokubectl apply
, assuming the context validation succeeds. Similarly, arguments tokubectl safe-delete
are passed tokubectl delete
. -
If any objects in the YAML file don't have the correct context annotation, nothing will be applied.
-
The
safe-apply/require-context
annotation must be present for the apply to succeed, as demonstrated above. This means you can't accidentally apply a normal YAML file to an important cluster just by forgetting to add the annotation. If you're usingsafe-apply
, you can trust that every object being applied explicitly names the context you're applying it to. -
You don't have to use stateful context selection.
--context
will also work:$ kubectx default $ kubectl safe-apply --context my-production-cluster -f my-file.yaml pod/my-pod configured
-
If it's safe to apply a particular YAML file to multiple clusters, you can specify them as a list in the annotation:
... annotations: safe-apply/require-context: - my-production-cluster - another-cluster ...