I find it useful to frontload my terminals with context about my environment; You wouldn’t want to deploy to the wrong environment now would you?
Here I extract information from Google Cloud CLI and print it at the start of every new terminal tab in order to understand exactly where my Google Cloud API requests will go by default.
GCP $GCP_APP_CRED_PROJECT=my-project GCP $GCP_CONFIGURATION=my-project GCP $GCP_PROJECT=my-project
Now we could use gcloud
to get each of these values but we would incur a significant time and processing cost, to illustrate this point, it takes gcloud
0.46 seconds to print our configuration, whereas reading the same file directly takes 0.002 seconds. Only reading a few variables adds up to 1.38 seconds versus 0.006 seconds delay to our terminal being ready to go.
gcloud
is a hugely featureful Python application for interacting with
Google Cloud
, but nothing can compare to reading files directly. It’s thanks to gcloud
saving these variables to disk in a readable format that we can save time like this.
Here is the bash script I use to populate my environment:
if [ -d "${HOME}/.config/gcloud" ]; then
# Current gcloud config configuration
export GCP_CONFIGURATION="$(< ${HOME}/.config/gcloud/active_config )"
# Set GCP_PROJECT to current default project
if [ ! "${GCP_PROJECT}" ] && [ "${GCP_CONFIGURATION}" ]; then
export GCP_PROJECT="$( /bin/awk '/project/ {print $3}' ${HOME}/.config/gcloud/configurations/config_${GCP_CONFIGURATION} 2>/dev/null )"
fi
# Set GCP_APP_CRED_PROJECT to Default Application Credentials (Uses the quota_project_id field)
export GCP_APP_CRED_PROJECT="$( awk -F'[:"]' '/quota_project_id/ {print $5}' ${HOME}/.config/gcloud/application_default_credentials.json 2>/dev/null )"
fi
These variables are as follows:
$GCP_CONFIGURATION
is read directly from${HOME}/.config/gcloud/active_config
$GCP_PROJECT
comes from theproject
field in${HOME}/.config/gcloud/configurations/config_${GCP_CONFIGURATION}
$GCP_APP_CRED_PROJECT
extracts the Default Application Credentials project from thequota_project_id
field in${HOME}/.config/gcloud/application_default_credentials.json
I hope this helps to save at least one “Uh-oh, where did that deploy to?”