The gcloud CLI

Google Cloud · Essentials · 12 min

gcloud is how you script, automate and reproduce everything you click in the console.

The gcloud CLI (part of the Google Cloud SDK, alongside bq and the legacy gsutil) drives almost every service. Commands follow gcloud GROUP [SUBGROUP] ACTION, e.g. gcloud compute instances list.

Getting set up:

  • gcloud init signs you in and picks a default project and region.
  • gcloud auth login authenticates the CLI itself as your user.
  • gcloud config set project ID and gcloud config set compute/region europe-west1 set defaults, so you can omit --project and --region.

Configurations are named sets of these properties. Create one per context (dev, prod, a client) and switch with gcloud config configurations activate prod. Pass --configuration or --project for one-off commands.

A service must be enabled in a project before its API can be used: gcloud services enable run.googleapis.com. A "SERVICE_DISABLED" or "API has not been used in project" error means exactly this.

For scripting, every list or describe command accepts --format (json, yaml, value(field), table(...)) and --filter (server- or client-side filtering on fields). value() gives bare values, perfect for shell variables.

Prefix beta or alpha to reach preview features, and add --help to any command for its full reference.

Example

gcloud config configurations create dev
gcloud config set project shop-dev-4821
gcloud config set compute/region europe-west1
gcloud config configurations list          # IS_ACTIVE marks the current one

gcloud services enable run.googleapis.com artifactregistry.googleapis.com
gcloud services list --enabled --filter="name:run" --format="value(name)"
# run.googleapis.com

# Capture a value for scripting
PROJECT_NUMBER=$(gcloud projects describe shop-dev-4821 --format="value(projectNumber)")
echo $PROJECT_NUMBER                        # 987654321098

Remember

  • Use named configurations to switch between projects safely
  • Enable an API before using its service
  • --format=value(...) and --filter make gcloud scriptable

Watch out for

  • Running a destructive command against the wrong project because the active configuration was not the one you assumed.

Check yourself

  1. A command fails with 'API has not been used in project ... or it is disabled'. What is the fix?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: cloud.google.com/sdk/docs/initializing