Kubernetes: copying a secret from one namespace to another

If you need to copy a secret from one namespace to another, you will get an error because the ‘namespace’ is still embedded in the yaml and cannot be overridden with the final apply.

By using a sed replacement as a filter, you can do a quick transformation and get your desired result.  Below is an example of copying over a secret from the ‘nginx-ns’ namespace to the ‘default’ namespace.

kubectl get secret my-tlssecret --namespace=nginx-ns -o yaml | sed 's/namespace: .*/namespace: default/' | kubectl apply -f -

It appears that ‘–export’ flag (now deprecated) used to be able to handle this use case.  Other CRD might require more extensive cleanup, and you can either use jq to remove json elements, or the kubectl neat plugin.

REFERENCES

stackoverflow, kubectl using jq delete to strip out unwanted portions

github, kubectl neat plugin that removes extra cruft

medium jonathan.johnson, same idea also used sed for namespace filter replacement