It's a fairly long command, but it actually is pretty easy use. You will however need to have yq installed as we need to scrub out a few elements from our YAML that are automatically created by Kubernetes. yq is just like jq but for working with YAML.
If we have a secret named database
in the namespace app-dev
and we want to copy it, as is, to the app-production
namespace we need to execute:
$ kubectl -n app-dev get secret database -o yaml | \
yq 'del(.metadata.creationTimestamp, .metadata.uid, .metadata.resourceVersion, .metadata.namespace)' | \
kubectl apply --namespace app-production -f -
Breakdown
What we're doing here is grabbing the current secret in YAML format. We then use yq
to remove the uid, namespace, creationTimestamp, and resourceVersion elements from the metadata stanza so it can be applied into a new namespace.
just
If you're a fan of the tool just like we are, you can drop in this command into your Justfile
:
# Copy a secret from one namespace to another
copy-secret from-namespace secret-name to-namespace:
kubectl -n {{from-namespace}} get secret {{secret-name}} -o yaml| yq 'del(.metadata.creationTimestamp, .metadata.uid, .metadata.resourceVersion, .metadata.namespace)' | kubectl apply --namespace {{to-namespace}} -f -
This can then be used quickly like:
$ just copy-secret app-dev pg app-production
Original Deprecated Example
UPDATE: Unfortunately, the --export
has been deprecated by the kubectl team so this original advice below no longer works with modern Kubernetes clusters.
The secret resource-type is unique--it cannot be accessed from pods outside of
its namespace. A simple way of copying common secret data (e.g.: docker registry credentials) between namespaces is provided by the --export
flag of kubectl get
. Pipe its output to kubectl apply -n <target namespace> -f -
, and you are done!
kubectl get secret gitlab-registry --namespace=revsys-com --export -o yaml |\ kubectl apply --namespace=devspectrum-dev -f -