DS DevShelfHub Projects · AI tools
Cheatsheets / gcloud CLI
Cheatsheet · Dev tooling

gcloud CLI Cheatsheet: IAM, Cloud Run and GCS Reference

By DevShelfHub

auth, projects, IAM, Compute, GCS, GKE, Cloud Run, Functions, IAM policies, logging, --format/--filter — the day-to-day gcloud surface.

120 items 9 min Projects IAM Run

Start hereQuick start · 6 you’ll reach for daily

Who am Igcloud auth list
Switch projectgcloud config set project P
Switch configgcloud config configurations activate dev
Deploy Rungcloud run deploy svc --image=…
Read logsgcloud logging read 'severity>=ERROR'
Table output--format="table(name,zone.basename())"

Target versions · paceVersions

Targets: gcloud ≥ 500 configurations ADC

The CLI follows rapid releases — pin in CI via the google-cloud-sdk:SLUG Docker tag. Many surfaces have moved: gsutilgcloud storage, gcloud functions deploy defaults to gen-2, Container RegistryArtifact Registry. ADC is now the path libraries use — not the user creds from gcloud auth login.

install · auth · configSetup

bash
# install (macOS — Homebrew cask)
brew install --cask gcloud-cli

# install (Linux — bundled tarball)
curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-linux-x86_64.tar.gz
tar -xf google-cloud-cli-linux-x86_64.tar.gz && ./google-cloud-sdk/install.sh

# verify
gcloud --version            # Google Cloud SDK 503+

# login: human (browser)
gcloud auth login
gcloud config set project my-project
gcloud config set compute/region us-central1
gcloud config set compute/zone   us-central1-a

# login: workload (service account JSON — CI, local emulation)
gcloud auth activate-service-account --key-file=key.json

# login: Application Default Credentials (libraries read these)
gcloud auth application-default login

# named configurations (multi-project)
gcloud config configurations create dev
gcloud config configurations activate dev   # like AWS profiles
gcloud config configurations list

projects · configurationsProjects & config

gcloud projects listAll projects you can see.
gcloud projects describe my-projectNumber, name, parent org/folder.
gcloud projects create my-project --organization=ORG_IDNew project under an org.
gcloud config set project my-projectPin project for current config.
gcloud config set compute/region us-central1Default region for compute APIs.
gcloud config listResolved values for the active configuration.
gcloud config configurations create devNamed configuration (project + region + account).
gcloud config configurations activate devPreferred Multi-account switching.
gcloud services list --enabledAPIs enabled on current project.
gcloud services enable run.googleapis.comTurn on an API. Many commands fail until you do.
gcloud --project=P --account=A storage lsOne-shot override for any command.

accounts · service accounts · ADCAuth & identity

gcloud auth loginBrowser-based human login.
gcloud auth listAll cached identities; active one is starred.
gcloud auth revoke EMAILSign out one account.
gcloud auth activate-service-account --key-file=key.jsonService-account login (CI, scripts).
gcloud auth application-default loginPreferred Writes ADC for client libraries.
gcloud auth application-default print-access-tokenBearer token for ad-hoc curl.
gcloud auth print-identity-token --audiences=URLOIDC ID token for Cloud Run invokers.
gcloud iam service-accounts listAll SAs in the project.
gcloud iam service-accounts create ci --display-name="CI"Mint a service account.
gcloud iam service-accounts keys create key.json --iam-account=ci@PROJ.iam.gserviceaccount.comLong-lived key. Avoid if you can; use Workload Identity Federation instead.
gcloud iam workload-identity-pools create … --location=globalPreferred Keyless GitHub/AWS → GCP federation.

--format · --filter · --sort-byOutput & filters

--format=jsonDefault-ish. Pipe to jq.
--format=yamlHuman-readable; round-trips with deployment manifests.
--format="value(name)"Newline-separated bare values. Feed to xargs.
--format="table(name, zone.basename(), status)"Custom table with transforms.
--format="csv(name,status)"Spreadsheet export.
--filter="status=RUNNING AND labels.env=prod"Server-side filter expression.
--filter="name~'^web-.*'"Regex match operator.
--sort-by=~creationTimestampDescending sort (leading ~).
--limit=20Cap total results.
--page-size=200Per-API-call batch size.
--quietNo prompts; assume default answer. CI-safe.
--verbosity=debug --log-httpDump every HTTP call. Best debug aid.
bash
# --filter is server-side; --format is client-side projection.

# running VMs, sorted by name, projected to a table
gcloud compute instances list \
  --filter="status=RUNNING AND labels.env=prod" \
  --sort-by=name \
  --format="table(name, zone.basename(), machineType.basename(), status, networkInterfaces[0].networkIP)"

# IDs only — feed straight into xargs
gcloud compute instances list --filter="labels.env=stale" \
  --format="value(name)" \
  | xargs -I{} gcloud compute instances delete {} --quiet

# JSON of a single resource
gcloud run services describe my-svc --region us-central1 --format=json | jq .

# CSV export
gcloud projects list --format="csv(projectId,name,projectNumber)" > projects.csv

instances · SSH · imagesCompute Engine

gcloud compute instances listAll VMs in current project.
gcloud compute instances describe NAME --zone=ZFull instance metadata.
gcloud compute instances create web --machine-type=e2-small --image-family=debian-12 --image-project=debian-cloudLaunch a VM from a public image.
gcloud compute instances start NAME --zone=ZPower on.
gcloud compute instances stop NAME --zone=ZPower off. Disk retained.
gcloud compute instances delete NAME --zone=ZDestructive. Default also deletes boot disk.
gcloud compute ssh NAME --zone=ZSSH via IAP tunneling. No public IP needed.
gcloud compute scp file NAME:/tmp/ --zone=ZCopy files over the same tunnel.
gcloud compute ssh NAME --zone=Z --tunnel-through-iap --command="systemctl status nginx"One-shot remote command.
gcloud compute disks list / snapshots createDisk inventory + snapshot.
gcloud compute firewall-rules listVPC firewall rules.
gcloud compute addresses create static-ip --region=us-central1Reserve a static external IP.

buckets · objects · signingCloud Storage

gcloud storage buckets listPreferred Replaces gsutil ls.
gcloud storage buckets create gs://my-bucket --location=us-central1 --uniform-bucket-level-accessNew bucket with UBLA on.
gcloud storage ls gs://my-bucket/path/ --recursiveTree listing.
gcloud storage cp file gs://my-bucket/keySingle upload.
gcloud storage cp -r ./dist gs://my-bucket/Recursive upload.
gcloud storage rsync ./dist gs://my-bucket --delete-unmatched-destination-objectsSync with deletes.
gcloud storage rm -r gs://my-bucket/path/Delete by prefix.
gcloud storage objects describe gs://b/kMetadata + storage class + generation.
gcloud storage sign-url gs://b/k --duration=1h --private-key-file=sa.jsonTime-limited signed URL.
gcloud storage buckets update gs://b --lifecycle-file=lifecycle.jsonSet a lifecycle policy from JSON.
gsutil cp …Legacy Still works; use gcloud storage in new scripts.

roles · bindings · policyIAM

gcloud iam roles list --filter="stage=GA"Curated GA roles.
gcloud iam roles describe roles/run.adminPermissions inside a predefined role.
gcloud iam roles create deployer --project=P --permissions=run.services.update,run.services.getCustom role at the project scope.
gcloud projects get-iam-policy PFull policy. Big; flatten for grep.
gcloud projects add-iam-policy-binding P --member=user:a@x --role=roles/viewerGrant a role to a principal.
gcloud projects remove-iam-policy-binding P --member=user:a@x --role=roles/viewerRevoke.
gcloud storage buckets add-iam-policy-binding gs://b --member=… --role=…Resource-scoped binding example.
gcloud iam service-accounts add-iam-policy-binding SA --member=serviceAccount:OTHER --role=roles/iam.serviceAccountTokenCreatorLet one SA impersonate another.
gcloud iam policies lint --resource=… --policy-file=p.jsonFind unused / over-broad bindings.
gcloud asset search-all-iam-policies --scope=organizations/ORG_ID --query="policy:alice@example.com"Org-wide blast-radius lookup for a principal.
bash
# grant a role at the project level
gcloud projects add-iam-policy-binding my-project \
  --member="serviceAccount:ci@my-project.iam.gserviceaccount.com" \
  --role="roles/run.admin" \
  --condition=None

# revoke
gcloud projects remove-iam-policy-binding my-project \
  --member="serviceAccount:ci@my-project.iam.gserviceaccount.com" \
  --role="roles/run.admin"

# resource-scoped binding (bucket)
gcloud storage buckets add-iam-policy-binding gs://my-bucket \
  --member="user:alice@example.com" \
  --role="roles/storage.objectViewer"

# who can do what — flatten the policy for grep-ability
gcloud projects get-iam-policy my-project \
  --flatten="bindings[].members" \
  --format="table(bindings.role, bindings.members)" \
  --filter="bindings.members:alice@example.com"

serverless containersCloud Run

gcloud run services listAll services in region(s).
gcloud run deploy SVC --image=IMG --region=R --allow-unauthenticatedDeploy or update a service.
gcloud run deploy SVC --source=. --region=RBuildpack flow — no Dockerfile needed.
gcloud run services describe SVC --region=RURL, revision, env, scaling.
gcloud run services update SVC --region=R --memory=1Gi --cpu=2 --concurrency=80Resize without redeploying code.
gcloud run services update SVC --region=R --set-env-vars=LOG=info --set-secrets=API_KEY=api-key:latestEnv + Secret Manager mount.
gcloud run services update-traffic SVC --to-revisions=SVC-00007=10,SVC-00006=90 --region=RCanary traffic split.
gcloud run services add-iam-policy-binding SVC --member=allUsers --role=roles/run.invoker --region=RMake a service public.
gcloud run jobs create JOB --image=IMG --region=R --task-timeout=10mBatch-style job (no request lifecycle).
gcloud run jobs execute JOB --region=R --waitTrigger a job execution and block.
gcloud run services logs tail SVC --region=RLive stdout/stderr.

clusters · credentialsGKE

gcloud container clusters listClusters in current project.
gcloud container clusters create-auto my-cluster --region=RPreferred GKE Autopilot (managed nodes).
gcloud container clusters create my-cluster --num-nodes=3 --zone=ZLegacy Standard cluster, you manage nodes.
gcloud container clusters get-credentials my-cluster --region=RWrites kubeconfig so kubectl talks to this cluster.
gcloud container node-pools list --cluster=my-clusterNode-pool inventory.
gcloud container clusters upgrade my-cluster --master --cluster-version=1.30Bump control plane.
gcloud container clusters delete my-cluster --region=RDestructive. Removes all node pools.

functions · artifact registryFunctions & Artifact Registry

gcloud functions deploy fn --gen2 --region=R --runtime=python312 --trigger-http --source=. --entry-point=mainGen-2 HTTP function. Runs on Cloud Run under the hood.
gcloud functions deploy fn --gen2 --trigger-event-filters="type=google.cloud.storage.object.v1.finalized" --trigger-event-filters="bucket=my-bucket"Event-driven (Eventarc).
gcloud functions listAll functions in current project.
gcloud functions logs read fn --region=R --limit=50Recent invocations + errors.
gcloud artifacts repositories create app --repository-format=docker --location=usNew Artifact Registry repo.
gcloud auth configure-docker us-docker.pkg.devRegister Docker credential helper for AR host.
gcloud artifacts docker images list us-docker.pkg.dev/P/appImages in a repo.
gcloud builds submit --tag=us-docker.pkg.dev/P/app/svc:v1Build + push via Cloud Build.
gcloud builds submit --pack image=us-docker.pkg.dev/P/app/svc:v1Buildpack (Dockerfile-free) build.

read · tail · sinksLogging

gcloud logging logs listLog names in project.
gcloud logging read 'severity>=ERROR' --limit=50 --format=jsonRecent errors as JSON.
gcloud logging tail 'resource.type="cloud_run_revision"' --buffer-window=1sLive tail. Filter is required.
gcloud logging metrics create m --log-filter='severity>=ERROR'Log-based metric (alert on it).
gcloud logging sinks create s storage.googleapis.com/B --log-filter='severity>=WARNING'Export logs to a GCS bucket.
gcloud logging sinks listWhere logs flow out of project.
bash
# live tail (follow) — like aws logs tail
gcloud logging tail "resource.type=cloud_run_revision AND severity>=ERROR" --buffer-window=1s

# one-shot, last 1h, last 100 entries
gcloud logging read \
  'resource.type="cloud_run_revision"
   AND resource.labels.service_name="my-svc"
   AND severity>=WARNING
   AND timestamp>="2026-05-19T00:00:00Z"' \
  --limit=100 --format=json | jq '.[].textPayload'

# filter by trace, follow a request across services
gcloud logging read \
  "trace=\"projects/$PROJECT/traces/abc123\"" \
  --format="table(timestamp, resource.labels.service_name, textPayload)"

# create a log-based metric (alertable)
gcloud logging metrics create error-rate \
  --description="ERROR-level Cloud Run logs" \
  --log-filter='resource.type="cloud_run_revision" AND severity>=ERROR'

build · secret · deploy · tailEnd-to-end · Cloud Run service

Buildpacks turn the working dir into an image, Secret Manager holds the API key, and Cloud Run scales to zero. Four commands, no Dockerfile, no YAML.

bash
# end-to-end: build + deploy a container to Cloud Run, wire up a secret
PROJECT=my-project
REGION=us-central1
SVC=hello

# 1) buildpacks: source → image, no Dockerfile needed
gcloud builds submit --pack image=us-docker.pkg.dev/$PROJECT/app/$SVC:v1

# 2) create a secret and let the service read it
echo -n "s3cr3t" | gcloud secrets create api-key --data-file=-
gcloud secrets add-iam-policy-binding api-key \
  --member="serviceAccount:$PROJECT-compute@developer.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor"

# 3) deploy: public, autoscaling, secret mounted as env var
gcloud run deploy $SVC \
  --image=us-docker.pkg.dev/$PROJECT/app/$SVC:v1 \
  --region=$REGION \
  --allow-unauthenticated \
  --memory=512Mi --cpu=1 --max-instances=10 \
  --set-secrets=API_KEY=api-key:latest

# 4) tail logs
gcloud run services logs tail $SVC --region=$REGION

Best practiceGood to know

Use configurations like AWS profiles. gcloud config configurations create dev / activate dev bundles project + region + account — flip between environments in one command, no shell-env hacks.
--format=value(name) is the secret to scripting. It strips quotes, headers, and newlines so the result composes with xargs and while read. Don’t reach for jq until you actually need nested fields.
Prefer Workload Identity Federation over service-account keys. Keys leak. WIF lets GitHub Actions / AWS / Azure assume a GCP identity using short-lived OIDC tokens — same blast-radius story as IAM roles vs IAM users.

Common trapsWatch out for

APIs aren’t enabled by default. Every first command against a service in a new project fails with Service has not been used. Run gcloud services enable … — or copy the URL from the error and click Enable. Quotas + billing must also be live.
gcloud auth login ≠ Application Default Credentials. The first is the CLI’s identity. The second is what client libraries read. They’re separate caches — you need gcloud auth application-default login for SDK code to authenticate locally.
Resource names are region-scoped, but the CLI defaults are tricky. Many commands inherit zone/region from compute/region in config; others require --region explicitly. If you get not found for a resource you just created, the CLI is probably looking in the wrong region.

Go deeperSee also

gcloud CLI FAQ

What is gcloud used for?

gcloud is the Google Cloud command-line tool for creating, configuring, and managing GCP resources — compute instances, Cloud Run services, GCS buckets, GKE clusters, IAM policies, and more. It is the primary interface for CI/CD automation and day-to-day operations on Google Cloud.

What is the difference between gcloud auth login and gcloud auth application-default login?

gcloud auth login sets credentials for the gcloud CLI itself (user identity for interactive commands). gcloud auth application-default login (ADC) sets credentials used by client libraries (Python, Node, Go, etc.) when they call GCP APIs. For running code locally, you need ADC; for CLI commands, you need gcloud auth login.

How do I switch between Google Cloud projects with gcloud?

Run gcloud config set project PROJECT_ID to switch the active project. For managing multiple project/account combinations, use named configurations: gcloud config configurations create dev sets up a new config, and gcloud config configurations activate dev switches to it. List all with gcloud config configurations list.

How does --format work in gcloud commands?

The --format flag controls output format. Use --format=json for full JSON, --format='table(name,zone)' for a custom table, or --format='value(name)' to extract a single field for scripting. Combine with --filter='status=RUNNING' to pre-filter server-side before formatting.

What replaced gsutil in the gcloud CLI?

The gcloud storage commands replaced the standalone gsutil tool. Commands like gsutil cp, gsutil ls, and gsutil rm map to gcloud storage cp, gcloud storage ls, and gcloud storage rm respectively. gcloud storage is faster for parallel transfers and is the preferred path for new scripts.

Is the gcloud CLI free to use?

The gcloud CLI itself is free to install and use. However, the GCP resources it creates (VMs, storage, Cloud Run, etc.) incur usage charges. Google Cloud offers a free tier for many services and a $300 credit for new accounts.