Created
November 14, 2023 05:18
-
-
Save marcinantkiewicz/307a7473ecc96275b91ef5be201787b0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env sh | |
while getopts sf:p ARG | |
do | |
case "${ARG}" in | |
s) SHORT_LIST=1;; | |
f) FILEPATH=${OPTARG};; | |
p) PULL=1;; | |
*) echo "\nReads GCP cloudbuild config, lists secrets contained in the file\n\nUsage: $(basename $0) [-s] -f filename\n -s short output, do not display google secrets path\n -f cloudbuild config to read\n -p list values for the secrets from GCP, in a format ready to be exported into bash\n\n" && exit 1; | |
esac | |
done | |
function check_file { | |
FILE=$1; shift; | |
set -e | |
test -r "$FILE" -a -f "$FILE" || \ | |
(>&2 echo "Error: file \"$FILE\" not found or unreadable"; exit 255); | |
} | |
# - list from the cloudbuild file | |
# one output shows just the list of defined secrets | |
# the other one appends path in GCP secrets manager for that entry | |
function list_secrets { | |
MANIFEST=$1; shift; | |
check_file "$MANIFEST" | |
set -o pipefail | |
PROJECT_ID=$(gcloud projects list --filter $(gcloud config get project) --format="value(PROJECT_NUMBER)") | |
test -n "${SHORT_LIST}" -a test -z ${PULL} && \ | |
SECRETS=$(cat "${MANIFEST}" | jq -r '.availableSecrets.secretManager[] | .env') || \ | |
SECRETS=$(cat "${MANIFEST}" | jq -r '.availableSecrets.secretManager[] | .env + "=" + .versionName'); | |
SECRETS="${SECRETS//\$PROJECT_ID/$PROJECT_ID}"; | |
echo "$SECRETS" | |
} | |
# - copies secrets into statements that can be used to import them into shell env ("export NAME="whatever"), this is meant to pull dev values for local development | |
function pull_secrets { | |
MANIFEST=$1; shift; | |
check_file "$MANIFEST" | |
PROJECT_ID=$(gcloud projects list --filter $(gcloud config get project) --format="value(PROJECT_NUMBER)") | |
set -o pipefail | |
for SECRET in $(list_secrets $MANIFEST); do | |
SECRET_ENV=$(echo "$SECRET" | cut -d '=' -f 1); | |
SECRET_PATH=$(echo "$SECRET" | cut -d '=' -f 2); | |
SECRET_NAME=$(echo "$SECRET_PATH" | cut -d '/' -f 4); | |
echo "export ${SECRET_ENV}=\"$(gcloud secrets versions access latest --secret=$SECRET_NAME --project=$PROJECT_ID)\""; | |
done | |
} | |
if test -n ${PULL} | |
then | |
pull_secrets "$FILEPATH" | |
else | |
list_secrets "$FILEPATH"; | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment