Skip to content.

Google Cloud CLI 'gcloud' Variables

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_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 )" 

    # 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 )"


These variables are as follows:

  • $GCP_CONFIGURATION is read directly from ${HOME}/.config/gcloud/active_config
  • $GCP_PROJECT comes from the project field in ${HOME}/.config/gcloud/configurations/config_${GCP_CONFIGURATION}
  • $GCP_APP_CRED_PROJECT extracts the Default Application Credentials project from the quota_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?”

Joe Heaton
Cloud HPC Engineer

Joe Heaton’s technology-focused murmurings.
comments powered by Disqus


Reveal the cookie consent prompt

Use Dyslexia-friendly font OpenDyslexia

Toggle advertisements