Skip to content

Instantly share code, notes, and snippets.

@adrienjoly
Last active February 23, 2022 16:25
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 adrienjoly/314e69e90cf4933bd8a5412e42e37e68 to your computer and use it in GitHub Desktop.
Save adrienjoly/314e69e90cf4933bd8a5412e42e37e68 to your computer and use it in GitHub Desktop.
This script returns the value of the latest enabled revision of the requested GCP secret.
# This script returns the value of the latest enabled revision of the requested secret.
# Usage: get-last-active-gcp-secret-revision.sh <secret-name>
SECRET_NAME=$1; shift;
if [ -z ${SECRET_NAME} ]; then
echo "Error: please specify the name of the secret to get."
echo "Available secrets:"
gcloud secrets list
exit 1
fi
set -e
LATEST_REVISION=$(gcloud secrets versions list "${SECRET_NAME}" \
--filter='state:enabled' --limit=1 --format='value(name)')
gcloud secrets versions access "${LATEST_REVISION}" --secret="${SECRET_NAME}"
@thetimbecker
Copy link

Thanks for this, it has been very helpful! It's a pain that if you disable or destroy the latest version, the latest alias stops being useful. It would be nice if they added another alias to get the latest enabled version.

I modified this script to effectively "refresh" the latest alias, adding a new secret version equivalent to the latest enabled one. I also added the option to specify a project, which I often have to do.

refresh-latest-secret-version.sh

# This script adds a version to a secret equal to the value of the latest enabled revision.
# This effectively resets the `latest` alias.

# Usage: refresh-latest-secret-version.sh <secret-name> [<project-id>]

SECRET_NAME=$1; shift;
PROJECT=$1; shift;

if [ -z ${SECRET_NAME} ]; then
    echo "Error: please specify the name of the secret to get."
    echo "Available secrets:"
    gcloud secrets list --project="$PROJECT"
    exit 1
fi

if [ -z ${PROJECT} ]; then
    PROJECT=$(gcloud config get-value project)
fi

set -e

LATEST_REVISION_NUMBER=$(gcloud secrets versions list "${SECRET_NAME}" \
    --filter='state:enabled' --project="$PROJECT" --limit=1 --format='value(name)')

LATEST_REVISION=$(gcloud secrets versions access "${LATEST_REVISION_NUMBER}" \
    --secret="${SECRET_NAME}" --project="$PROJECT")

echo $LATEST_REVISION | gcloud secrets versions add $SECRET_NAME --project="$PROJECT" --data-file=-

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment