Skip to content

Instantly share code, notes, and snippets.

@JohnMcSpedon
Created June 30, 2022 22:10
Show Gist options
  • Save JohnMcSpedon/3b3af4dfc14ea6df8623b8a7d740d290 to your computer and use it in GitHub Desktop.
Save JohnMcSpedon/3b3af4dfc14ea6df8623b8a7d740d290 to your computer and use it in GitHub Desktop.
authorize a new google cloud project. save its default application credentials, so that it's easy to switch between projects
#@IgnoreInspection BashAddShebang
GCLOUD_DIR="$HOME/.config/gcloud"
: ${PROJECT_NAME?"Need to set PROJECT_NAME"}
if curl metadata.google.internal -i &> /dev/null; then
echo "Running on GCE instance. Skipping $PROJECT_NAME setup"
else
# https://stackoverflow.com/a/28938235/3893740
GREEN='\033[0;32m'
COLOR_OFF='\033[0m'
if [[ ! -f $GCLOUD_DIR/configurations/config_$PROJECT_NAME ]]; then
echo -e "$GREEN"
echo "################################################################################"
echo "Creating new gcloud configuration for the GCP Project $PROJECT_NAME."
echo "################################################################################"
echo ""
echo -e "$COLOR_OFF" # end color scheme
gcloud config configurations create $PROJECT_NAME
echo -e "$GREEN" # set color to green
echo ""
echo "################################################################################"
echo "Running gcloud init, please follow instructions from. In the following steps:"
echo "I Choose \"[1] Re-initialize this configuration [$PROJECT_NAME] with new settings\""
echo "II Choose to use appropriate email address"
echo "III Choose \"[#] $PROJECT_NAME\""
echo "IV Choose \"y\" for setting a default region".
echo "V Browser opens. Login using same gmail address"
echo "################################################################################"
echo ""
echo -e "$COLOR_OFF" # end color scheme
gcloud init
gcloud auth application-default login
cp $GCLOUD_DIR/application_default_credentials.json \
$GCLOUD_DIR/application_default_credentials.json.$PROJECT_NAME
echo "Finished setup for project $PROJECT_NAME"
fi
current_project=$( gcloud config list --format 'value(core.project)' 2> /dev/null )
if [ "$current_project" != "$PROJECT_NAME" ]; then
echo "Your current project is $current_project, but your config is set to $PROJECT_NAME. Please run $ switch_gcp_project $PROJECT_NAME"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment