Skip to content

Instantly share code, notes, and snippets.

@froblesmartin
Created February 16, 2024 02:55
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 froblesmartin/0af754020d32dbe9e6ad97d896494c22 to your computer and use it in GitHub Desktop.
Save froblesmartin/0af754020d32dbe9e6ad97d896494c22 to your computer and use it in GitHub Desktop.
Copy GCP Secret Manager secrets to a different project
#!/bin/zsh
function transform_output_to_array() {
local output="$1"
local array=()
local skip_first=true
while IFS= read -r line; do
if ${skip_first}; then
skip_first=false
continue
fi
array+=("${line}")
done <<< "${output}"
echo "${array[@]}"
}
RED='\033[0;31m'
NC='\033[0m'
SOURCE_GCP_PROJECT="your-source-project"
TARGET_GCP_PROJECT="your-target-project"
SECRETS_OUTPUT=$(gcloud secrets list --project=${SOURCE_GCP_PROJECT} --format="csv(name)")
SECRETS_ARRAY=($(transform_output_to_array "${SECRETS_OUTPUT}"))
TEMPORARY_DIRECTORY=$(mktemp -d -p .)
echo "Generated temporary directory: [${TEMPORARY_DIRECTORY}]"
# Loop over the array
for SECRET_NAME in "${SECRETS_ARRAY[@]}"; do
echo
echo "Secret name [${SECRET_NAME}]"
SECRET_VERSIONS_OUTPUT=$(gcloud secrets versions list --project=${SOURCE_GCP_PROJECT} --format="csv(name)" -- ${SECRET_NAME})
SECRETS_VERSIONS_ARRAY=($(transform_output_to_array "${SECRET_VERSIONS_OUTPUT}"))
echo "Versions: [${SECRETS_VERSIONS_ARRAY[@]}"]
SECRET_LABELS=""
while read -r KEY VALUE; do
SECRET_LABELS+="${KEY}=${VALUE},"
done < <(gcloud secrets describe --format="json" -- ${SECRET_NAME} | jq -r '.labels | to_entries | .[] | "\(.key) \(.value)"')
echo "Labels: [${SECRET_LABELS}]"
gcloud secrets create --project ${TARGET_GCP_PROJECT} --labels=${SECRET_LABELS} -- ${SECRET_NAME} || \
echo -e "${RED}Secret [${SECRET_NAME}] creation failed${NC}"
SECRETS_VERSIONS_ARRAY_LENGTH=${#SECRETS_VERSIONS_ARRAY[@]}
for ((i=${SECRETS_VERSIONS_ARRAY_LENGTH}-1; i>=0; i--)); do
echo "Processing version: ${SECRETS_VERSIONS_ARRAY[${i}]}"
gcloud secrets versions access ${SECRETS_VERSIONS_ARRAY[${i}]} --secret=${SECRET_NAME} --project=${SOURCE_GCP_PROJECT} > ${TEMPORARY_DIRECTORY}/${SECRET_NAME}_${SECRET_VERSION}
gcloud secrets versions access ${SECRETS_VERSIONS_ARRAY[${i}]} --secret=${SECRET_NAME} --project=${TARGET_GCP_PROJECT} >> /dev/null && \
{ echo -e "${RED}Version [${SECRETS_VERSIONS_ARRAY[${i}]}] already exists${NC}" && continue; }
gcloud secrets versions add --project ${TARGET_GCP_PROJECT} --data-file=${TEMPORARY_DIRECTORY}/${SECRET_NAME}_${SECRET_VERSION} -- ${SECRET_NAME}
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment