Skip to content

Instantly share code, notes, and snippets.

@megalucio
Created January 31, 2023 13:20
Show Gist options
  • Save megalucio/56063bbc39f0bbf32fcd98ee16f839e2 to your computer and use it in GitHub Desktop.
Save megalucio/56063bbc39f0bbf32fcd98ee16f839e2 to your computer and use it in GitHub Desktop.
Bash script to enable your public ip to access the project configured locally with gcloud
#!/bin/bash
# Bash script to enable your public ip to access the project configured locally with gcloud.
# If a rule already exists associated with this principal(set up as the description on creation time),
# the existing rule is updated instead of creating a new rule.
# You need to have gcloud installed and initialized with your principal and corresponding project you want to access to.
# A security policy with the name defined under the POLICY_NAME variable above must exist already in the project
# Input parameters
PRINCIPAL=$(gcloud auth list --filter=status:ACTIVE --format='value(ACCOUNT)')
POLICY_NAME='allowed-ips'
RANDOM_PRIORITY=$((1000 + RANDOM % 1000000))
MY_IP=$(curl -s ifconfig.me)
# Get the priority of the rule associated with the principal, if it exists
PRIORITY=$(gcloud compute security-policies describe $POLICY_NAME --format=json| jq ".[].rules[]| select(.description==\"$PRINCIPAL\") | .priority")
# If a match is not found, then a new rule neds to be created with random priority
if [ -z "${priority}" ]; then
gcloud compute security-policies rules create $RANDOM_PRIORITY \
--security-policy $POLICY_NAME \
--src-ip-ranges "$MY_IP" \
--action ALLOW \
--description=$PRINCIPAL
else
# If a match is found, then update the existing rule
gcloud compute security-policies rules update $PRIORITY \
--security-policy $POLICY_NAME \
--src-ip-ranges "$MY_IP" \
--action ALLOW \
--description=$PRINCIPAL
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment