How to Copy Secrets From One Kubernetes Cluster to Another

John John (304)
10 minutes

There are many reasons you might want to copy Kubernetes secrets from one cluster to another. In recent months, I had to migrate to a new GKE cluster in order to get some new functionality. And in this particular project, some secrets are created by processes that are too complicated to recreate on the new cluster. The easiest solution was simply to copy the secrets over.

So in this guide, I'll show you a few simple ways of copying secrets from one Kubernetes cluster to another.

Posted in these interests:
h/kubernetes7 guides

For the purposes of this guide, I'll refer to the two clusters are "source" and "destination". We want to copy a secret from our "source" cluster to our "destination" cluster.

So first, ensure you're authenticated with your source cluster.

kubectl config current-context

This should show the name of the context configured to access your source cluster.

Now export the secret, and store the secret config data in a file.

kubectl get secret my-secret-name --export -o yaml > my-secret-name.yaml

Now, you can import the secret into the new cluster. So go ahead and authenticate with the destination cluster, and simply apply the config file you just exported.

kubectl apply -f my-secret-name.yaml

Now confirm your secret was created properly.

kubectl get secret

This should show your newly created secret.

Now, a quick note on security. There are security risks associated with storing sensitive information on your file system (even if the file is deleted). In any case, you'll want to delete the file that was used to temporarily store the secret data, and only use this method if you understand the risks and are happy to accept them.

The first two steps were broken out, but can be combined into a single command.

First you'll need to get the context names for your two clusters. This command will help:

kubectl config get-contexts

Now you can run:

kubectl get secret my-secret-name --context source_context --export -o yaml | kubectl apply --context destination_context -f -

Hopefully you recognize some of the component parts of this script. We're skipping the part where we export the config to a file, and instead piping the config into kubectl apply. Notice that we can set the context for each kubectl command, this allows us to send data from one cluster to another. Beautiful!

Kubernetes is compatible with Superset which can help visualize data between multiple sources. Visit our guide for steps on how to install Apache Superset on a GKE Kubernetes Cluster.

John John (304)
10 minutes

If you're using Kubernetes, you may find the need to move files to and from containers running on pods.