Skip to content

Instantly share code, notes, and snippets.

@marcusschiesser
Last active November 23, 2022 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcusschiesser/0b6b36a1496cd68515870a6f5caa1ef5 to your computer and use it in GitHub Desktop.
Save marcusschiesser/0b6b36a1496cd68515870a6f5caa1ef5 to your computer and use it in GitHub Desktop.
Copy a K8S secret to another namespace. If the secret exists, it is updated.
#!/usr/bin/env bash
# Depedency: requires yq>=4.x and kubectl
if [ "$#" -ne 4 ]; then
echo "Usage: copy_secret <src_namespace> <src_secret_name> <dest_namespace> <dest_secret_name>"
exit 1
fi
function copy_secret {
local src_ns=$1
local src_name=$2
local dest_ns=$3
local dest_name=$4
kubectl get secret -n=$dest_ns $dest_name 1> /dev/null 2> /dev/null
exit_status=$?
if [ $exit_status -eq 0 ]; then
echo "Secret $dest_name in $dest_ns does already exist. Updating it with data from secret $src_name in $src_ns namespace."
export data=$(kubectl get secret -n=$src_ns $src_name -oyaml | yq '.data')
kubectl get secret -n=$dest_ns $dest_name -oyaml | yq '.data=env(data)' | kubectl apply -f -
else
echo "Secret $dest_name in $dest_ns doesn't exist yet. Creating it with data from secret $src_name in $src_ns namespace."
kubectl get secret -n=$src_ns $src_name -oyaml | yq 'del( .metadata[] )' | yq ".metadata += {\"name\": \"$dest_name\"}" | kubectl apply -n=$dest_ns -f -
fi
}
copy_secret $1 $2 $3 $4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment