gcloud auth list && gcloud config get-value project

GCP CLI
Production Surface

~28 entries distilled to what engineers with production scars actually reach for. Honest about what belongs in Terraform or the console.

28 entries
7 phases
gcloud SDK, multi-project
What's not here, and why. gcloud deployment-manager: Terraform does this better. gcloud builds: Cloud Build is console/YAML territory, not interactive CLI ops. gcloud app: App Engine is legacy; use Cloud Run. bq: BigQuery has its own CLI; it's not a gcloud subcommand. gcloud dataflow / dataproc / bigtable: SDK territory. gcloud beta / alpha commands, not stable enough for a production reference. gsutil vs gcloud storage: Google is actively migrating storage ops from gsutil to gcloud storage. This page uses gcloud storage throughout; install the latest SDK to get it.
cross-cutting: know these before anything else
auth patterns
gcloud auth login gcloud auth activate-service-account --key-file=sa-key.json gcloud auth application-default login gcloud auth list # ADC vs gcloud auth: different credential stores # ADC is used by client libraries; gcloud auth by the CLI
project / config context
gcloud config set project my-project-id gcloud config get-value project gcloud config configurations create prod gcloud config configurations activate prod gcloud config configurations list # or per-command: --project=my-project-id
--format + --filter (not JMESPath)
gcloud compute instances list --format="table(name,zone,status,networkInterfaces[0].networkIP)" gcloud compute instances list --filter="status=RUNNING AND zone:us-central1" gcloud compute instances list --format=json | jq '.[].name' # --format: table, json, yaml, csv, value, flattened # --filter uses GCP's own CEL-like syntax, not JMESPath
named configurations (multi-account)
gcloud config configurations create staging gcloud config set project staging-project-id gcloud config set account staging@example.com gcloud config set compute/region europe-west1 # switch configs: gcloud config configurations activate prod # or per-command: --configuration=prod
Phase 28 shown
Service / CommandPhaseKey commandsUse case
gcloud auth auth
gcloud auth login --update-adc gcloud auth activate-service-account sa@project.iam.gserviceaccount.com --key-file=sa-key.json gcloud auth activate-service-account --key-file=sa-key.json gcloud auth application-default login gcloud auth application-default set-quota-project my-project gcloud auth revoke --all
--update-adc sets both the gcloud credential and ADC simultaneously. Use in local dev to avoid the common mistake of forgetting to run application-default login separately. In CI, always use a service account key file or Workload Identity Federation. Never interactive login. set-quota-project is required when ADC would otherwise bill an unexpected project.
service accounts auth
gcloud iam service-accounts list --project=my-project --format="table(email,displayName,disabled)" gcloud iam service-accounts describe sa@project.iam.gserviceaccount.com gcloud iam service-accounts keys list --iam-account=sa@project.iam.gserviceaccount.com --format="table(name.basename(),validAfterTime,validBeforeTime)" gcloud iam service-accounts keys delete KEY_ID --iam-account=sa@project.iam.gserviceaccount.com gcloud projects get-iam-policy my-project --format=json | jq '.bindings[] | select(.members[] | contains("serviceAccount:sa@"))'
Key listing with expiry dates surfaces stale keys: delete any key older than 90 days. get-iam-policy piped through jq audits what a specific service account can do. Run this before rotating a key to understand blast radius. Prefer Workload Identity over key files for workloads running in GCP; key files only for external systems.
gcloud projects / IAM auth
gcloud projects list --format="table(projectId,name,projectNumber,lifecycleState)" gcloud projects describe my-project gcloud projects get-iam-policy my-project --format=json | jq '.bindings[] | select(.role | contains("Owner","Editor"))' gcloud asset search-all-iam-policies --query="policy:sa@project.iam.gserviceaccount.com" --scope=projects/my-project gcloud auth print-access-token
The IAM policy JMESPath query surfaces any binding with Owner or Editor: basic-role bindings should be minimised in production projects. asset search-all-iam-policies finds where a principal has access across the entire project, not just the project-level IAM policy. print-access-token gets a bearer token for direct REST API calls.
gcloud compute instances compute
gcloud compute instances list --filter="status=RUNNING" --format="table(name,zone,machineType.basename(),networkInterfaces[0].networkIP,status)" gcloud compute instances describe my-vm --zone=us-central1-a gcloud compute instances start my-vm --zone=us-central1-a gcloud compute instances stop my-vm --zone=us-central1-a gcloud compute instances get-serial-port-output my-vm --zone=us-central1-a gcloud compute instances set-machine-type my-vm --zone=us-central1-a --machine-type=n2-standard-4
get-serial-port-output reads the VM console: the only way to diagnose boot failures on a VM you can't SSH into. set-machine-type resizes a stopped VM without reprovisioning. Provision via Terraform; use the CLI for runtime inspection and incident response. Note machineType.basename() strips the full URL to just the type name in table output.
gcloud compute ssh / IAP compute
gcloud compute ssh my-vm --zone=us-central1-a gcloud compute ssh my-vm --zone=us-central1-a --tunnel-through-iap gcloud compute start-iap-tunnel my-vm 5432 --local-host-port=localhost:15432 --zone=us-central1-a gcloud compute ssh my-vm --zone=us-central1-a -- "df -h && free -m" gcloud compute scp my-vm:/tmp/logfile.gz ./logfile.gz --zone=us-central1-a
IAP tunnel is the GCP equivalent of AWS SSM Session Manager: SSH without a public IP or open firewall port. Requires the IAP API enabled and appropriate IAM binding (roles/iap.tunnelResourceAccessor). start-iap-tunnel forwards a port through IAP: connects to Cloud SQL, Redis, or internal services without a bastion.
gcloud container (GKE) compute
gcloud container clusters list --format="table(name,location,currentNodeCount,currentMasterVersion,status)" gcloud container clusters get-credentials my-cluster --region=us-central1 gcloud container clusters describe my-cluster --region=us-central1 --format="yaml(currentMasterVersion,nodePools[].config.machineType,addonsConfig)" gcloud container node-pools list --cluster=my-cluster --region=us-central1 gcloud container node-pools update my-pool --cluster=my-cluster --region=us-central1 --enable-autoscaling --min-nodes=1 --max-nodes=10 gcloud container get-server-config --region=us-central1 --format="yaml(validMasterVersions[0:5])"
get-credentials writes the kubeconfig entry: --region for regional clusters, --zone for zonal. get-server-config lists available Kubernetes versions in a region. Check this before planning an upgrade window. addonsConfig in describe reveals which managed add-ons are enabled.
gcloud run compute
gcloud run services list --platform=managed --region=us-central1 --format="table(name,status.url,status.latestReadyRevisionName,status.traffic[0].percent)" gcloud run services describe my-service --region=us-central1 gcloud run services update my-service --region=us-central1 --min-instances=1 --max-instances=10 gcloud run revisions list --service=my-service --region=us-central1 --format="table(name,status.observedGeneration,spec.containerConcurrency,status.conditions[0].status)" gcloud run services update-traffic my-service --region=us-central1 --to-revisions=my-service-00010-abc=50,my-service-00009-xyz=50
Traffic splitting between revisions is the canonical Cloud Run canary deploy pattern: update-traffic with two revision names and percentages. revisions list shows which revisions are serving traffic and their concurrency settings. min-instances=1 eliminates cold starts for latency-sensitive services at the cost of always-on billing.
gcloud compute instance-groups compute
gcloud compute instance-groups managed list --format="table(name,zone,targetSize,status.isStable)" gcloud compute instance-groups managed list-instances my-mig --zone=us-central1-a --format="table(name,instance.basename(),instanceStatus,currentAction)" gcloud compute instance-groups managed resize my-mig --zone=us-central1-a --size=5 gcloud compute instance-groups managed recreate-instances my-mig --zone=us-central1-a --instances=my-vm-abc1 gcloud compute instance-groups managed describe-instance my-mig --zone=us-central1-a --instance=my-vm-abc1
list-instances with currentAction shows what the MIG is actively doing to each instance: RECREATING, DELETING, VERIFYING. recreate-instances replaces a specific unhealthy instance without touching the rest of the group. status.isStable confirms the MIG has converged to desired state.
gcloud storage (buckets) storage
gcloud storage buckets list --format="table(name,location,storageClass,iamConfiguration.publicAccessPrevention)" gcloud storage buckets describe gs://mybucket gcloud storage buckets get-iam-policy gs://mybucket --format=json | jq '.bindings[] | select(.members[] | contains("allUsers","allAuthenticatedUsers"))' gcloud storage buckets update gs://mybucket --no-uniform-bucket-level-access gcloud storage buckets update gs://mybucket --public-access-prevention=enforced
The IAM policy jq query surfaces any binding granting access to allUsers or allAuthenticatedUsers: these are the two values that make a bucket public. public-access-prevention=enforced blocks public access at the bucket level regardless of ACLs or IAM: the GCP equivalent of AWS's block-public-access setting.
gcloud storage (objects) storage
gcloud storage ls gs://mybucket/prefix/ --recursive --long gcloud storage cp ./file.tar.gz gs://mybucket/backups/ gcloud storage rsync ./local/ gs://mybucket/prefix/ --recursive --delete-unmatched-destination-objects gcloud storage sign-url gs://mybucket/private.zip --duration=1h --private-key-file=sa-key.json gcloud storage rm gs://mybucket/prefix/ --recursive --dry-run gcloud storage cp gs://mybucket/file.tar.gz - | tar xz
rsync --delete-unmatched-destination-objects is the GCS equivalent of aws s3 sync --delete: always run with --dry-run first. sign-url requires a service account key file: Workload Identity Federation can't generate signed URLs directly (a GCP limitation). Pipe cp to stdout for streaming decompression without a temp file.
gcloud compute firewall-rules networking
gcloud compute firewall-rules list --format="table(name,network,direction,priority,sourceRanges.list():label=SRC,allowed[].map().firewall_rule().list():label=ALLOW)" gcloud compute firewall-rules list --filter="sourceRanges:0.0.0.0/0 AND direction=INGRESS" --format="table(name,network,allowed[].map().firewall_rule().list())" gcloud compute firewall-rules describe my-rule gcloud compute firewall-rules create allow-https --network=my-vpc --allow=tcp:443 --source-ranges=0.0.0.0/0 --priority=1000 gcloud compute firewall-rules delete my-rule
The second command surfaces all ingress rules allowing traffic from any IP: the quick public-exposure audit. GCP firewall rules apply at the VPC level, not per-instance, and are evaluated by priority (lower = higher priority). describe shows target tags and service accounts: understanding these is critical since GCP uses tags, not security group IDs.
gcloud compute networks networking
gcloud compute networks list --format="table(name,autoCreateSubnetworks,subnetMode)" gcloud compute networks subnets list --network=my-vpc --format="table(name,region,ipCidrRange,privateIpGoogleAccess,secondaryIpRanges)" gcloud compute networks peerings list --network=my-vpc gcloud compute addresses list --format="table(name,address,addressType,status,region)" gcloud compute addresses list --filter="addressType=EXTERNAL" --format="table(name,address,status,users)"
subnets list with privateIpGoogleAccess confirms Private Google Access is enabled: required for VMs without external IPs to reach Google APIs. External address list with users shows which resources are using each static IP: unattached addresses (status=RESERVED, no users) incur charges and are worth cleaning up.
gcloud compute backend-services networking
gcloud compute backend-services list --global --format="table(name,protocol,healthChecks[].basename(),backends[].group.basename())" gcloud compute backend-services get-health my-backend --global --format=json | jq '.[]|{backend:.backendSummary.uri|split("/")|last,health:.status.healthStatus}' gcloud compute url-maps list --format="table(name,defaultService)" gcloud compute target-https-proxies list --format="table(name,urlMap,sslCertificates[].basename())"
get-health is the first command during a load balancer incident: shows per-backend health status from the LB's perspective, which may differ from the instance's own view. The URL map and HTTPS proxy chain confirms which SSL certificate is attached and which backend services are in the request path.
gcloud dns networking
gcloud dns managed-zones list --format="table(name,dnsName,visibility,dnssecConfig.state)" gcloud dns record-sets list --zone=my-zone --format="table(name,type,ttl,rrdatas)" gcloud dns record-sets describe api.example.com. --zone=my-zone --type=A gcloud dns record-sets transaction start --zone=my-zone gcloud dns record-sets transaction add 10.0.0.1 --name=api.example.com. --ttl=300 --type=A --zone=my-zone gcloud dns record-sets transaction execute --zone=my-zone
Cloud DNS record mutations use a transaction model: start, add/remove operations, execute or abort. This makes the change atomic and auditable. dnssecConfig.state confirms DNSSEC is enabled on the zone. Check before debugging why certain resolvers reject the domain. Note the trailing dot on record names: Cloud DNS requires it.
gcloud secrets secrets
gcloud secrets list --format="table(name,replication.automatic,createTime)" --project=my-project gcloud secrets versions access latest --secret=my-secret --project=my-project gcloud secrets versions access latest --secret=my-secret | jq -r '.password' gcloud secrets versions list my-secret --format="table(name,state,createTime)" echo -n "mysecretvalue" | gcloud secrets create new-secret --data-file=- --replication-policy=automatic gcloud secrets add-iam-policy-binding my-secret --member="serviceAccount:sa@project.iam.gserviceaccount.com" --role="roles/secretmanager.secretAccessor"
versions access latest fetches the current value: pipe through jq for structured secrets. The echo -n | --data-file=- pattern creates a secret from stdin without writing to a file or shell history. add-iam-policy-binding grants a specific service account access to a specific secret. Prefer this over project-level Secret Accessor bindings.
Workload Identity secrets
gcloud iam service-accounts get-iam-policy sa@project.iam.gserviceaccount.com --format=json | jq '.bindings[] | select(.role=="roles/iam.workloadIdentityUser")' gcloud iam service-accounts add-iam-policy-binding sa@project.iam.gserviceaccount.com --role="roles/iam.workloadIdentityUser" --member="serviceAccount:my-project.svc.id.goog[namespace/ksa]" gcloud container clusters describe my-cluster --region=us-central1 --format="value(workloadIdentityConfig.workloadPool)" # verify from inside a pod: gcloud auth print-access-token --impersonate-service-account=sa@project.iam.gserviceaccount.com
Workload Identity Federation links a Kubernetes service account to a GCP service account: no key files needed in pods. The IAM binding member format is exactly serviceAccount:PROJECT.svc.id.goog[NAMESPACE/KSA]: any typo silently fails. describe cluster confirms the workload pool is configured before debugging WIF binding issues.
gcloud logging observability
gcloud logging tail "resource.type=cloud_run_revision AND resource.labels.service_name=my-service" --format="value(timestamp,textPayload)" gcloud logging read "resource.type=gce_instance AND severity>=ERROR" --limit=50 --format="table(timestamp,resource.labels.instance_id,textPayload)" gcloud logging read "protoPayload.methodName=SetIamPolicy" --project=my-project --limit=20 --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.request.resource)" gcloud logging read "resource.type=k8s_container AND resource.labels.cluster_name=my-cluster AND textPayload:\"ERROR\"" --limit=100 --freshness=1h
logging tail is the live log equivalent of aws logs tail --follow: works for Cloud Run, GCE, GKE, and any resource type. The IAM audit log query (SetIamPolicy) surfaces who changed permissions and on what: essential for post-incident attribution. --freshness bounds the time range without specifying epoch timestamps.
gcloud monitoring observability
gcloud monitoring policies list --format="table(name,displayName,enabled,conditions[0].displayName)" gcloud monitoring policies describe POLICY_NAME gcloud monitoring dashboards list --format="table(name,displayName)" gcloud alpha monitoring metrics list --filter="metric.type:compute.googleapis.com" --format="table(metric.type)" | head -20 # for metric timeseries, use the Monitoring API directly: curl -H "Authorization: Bearer $(gcloud auth print-access-token)" "https://monitoring.googleapis.com/v3/projects/my-project/timeSeries?filter=metric.type%3D%22compute.googleapis.com%2Finstance%2Fcpu%2Futilization%22&interval.startTime=$(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%SZ)&interval.endTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
The gcloud monitoring CLI surface is thin: alert policy listing and description only. For metric timeseries, use the REST API with print-access-token for auth: the curl pattern shown is the pragmatic path. policies list during an incident confirms which alerts are configured and enabled before checking if they fired.
gcloud compute / uptime observability
gcloud compute operations list --filter="status!=DONE" --format="table(name,operationType,status,targetLink.basename())" gcloud compute operations describe OPERATION_NAME --global gcloud monitoring uptime list-configs --format="table(name,displayName,monitoredResource.type,period)" gcloud beta monitoring uptime describe CONFIG_NAME
In-progress compute operations (instance creation, disk attachment, snapshot) are visible via operations list --filter="status!=DONE": useful when a Terraform apply seems stuck and you want to see what GCP is actually doing. Uptime check configs confirm external health monitoring is in place before a production launch.
gcloud artifacts data / platform
gcloud auth configure-docker us-central1-docker.pkg.dev gcloud artifacts repositories list --location=us-central1 --format="table(name,format,createTime)" gcloud artifacts docker images list us-central1-docker.pkg.dev/my-project/my-repo --format="table(image,version,createTime)" gcloud artifacts docker images describe us-central1-docker.pkg.dev/my-project/my-repo/myapp:latest gcloud artifacts docker images scan us-central1-docker.pkg.dev/my-project/my-repo/myapp:latest --format=json | jq '.response.occurrences[] | select(.vulnerability.severity=="CRITICAL")' gcloud artifacts docker tags list us-central1-docker.pkg.dev/my-project/my-repo/myapp
configure-docker sets up Docker credentials for Artifact Registry: replaces the old gcloud auth configure-docker gcr.io pattern for GCR. images scan triggers Container Analysis vulnerability scanning: pipe through jq to surface CRITICAL findings only. Use Artifact Registry, not GCR (Container Registry): GCR is deprecated.
gcloud sql data / platform
gcloud sql instances list --format="table(name,databaseVersion,region,settings.tier,state)" gcloud sql instances describe my-instance --format="yaml(state,settings.backupConfiguration,settings.ipConfiguration,failoverReplica)" gcloud sql connect my-instance --user=postgres --database=mydb gcloud sql backups list --instance=my-instance --format="table(id,type,status,windowStartTime)" gcloud sql instances failover my-instance gcloud sql operations list --instance=my-instance --format="table(name,operationType,status,startTime)"
gcloud sql connect uses IAP to open a psql/mysql session without whitelisting your IP: requires cloud_sql_proxy or Cloud SQL Auth Proxy installed. describe with backupConfiguration confirms automated backups are enabled before a risky migration. operations list shows in-progress maintenance or failover operations.
gcloud pubsub data / platform
gcloud pubsub topics list --format="table(name)" gcloud pubsub subscriptions list --format="table(name,topic,pushConfig.pushEndpoint,ackDeadlineSeconds)" gcloud pubsub topics publish my-topic --message='{"type":"test","payload":"hello"}' gcloud pubsub subscriptions pull my-subscription --limit=5 --auto-ack gcloud pubsub subscriptions describe my-subscription --format="yaml(deadLetterPolicy,expirationPolicy,retryPolicy)" gcloud pubsub snapshots list
topics publish from the CLI is the fastest way to inject a test message into an event-driven pipeline. subscriptions pull --auto-ack peeks at messages for debugging without leaving them unacked. describe with deadLetterPolicy confirms a DLQ is configured: Pub/Sub without a DLQ silently drops unprocessable messages after max delivery attempts.
gcloud functions data / platform
gcloud functions list --format="table(name,status,trigger,runtime,region)" gcloud functions describe my-function --region=us-central1 gcloud functions call my-function --region=us-central1 --data='{"key":"value"}' gcloud functions logs read my-function --region=us-central1 --limit=50 gcloud functions add-invoker-policy-binding my-function --region=us-central1 --member="allUsers" # Gen 2 functions are Cloud Run under the hood: use gcloud run for traffic splitting
functions call invokes synchronously and returns the result: the fastest way to test a function without writing a curl command. logs read is function-scoped log tailing without writing a full Cloud Logging filter. Gen 2 functions run on Cloud Run: gcloud run commands work on them too and offer more operational control.
gcloud resource manager / asset data / platform
gcloud asset search-all-resources --scope=projects/my-project --asset-types="compute.googleapis.com/Instance" --format="table(name,location,additionalAttributes.status)" gcloud asset search-all-resources --scope=projects/my-project --query="labels.env:prod" --format="table(name,assetType,location)" gcloud resource-manager tags keys list --parent=projects/my-project gcloud asset list --project=my-project --asset-types="storage.googleapis.com/Bucket" --format="table(name,updateTime)"
Cloud Asset Inventory is the cross-service resource query API: find any resource type by label, location, or type without querying each service individually. search-all-resources --query="labels.env:prod" is the GCP equivalent of az resource list --tag env=prod: the fastest way to answer "what's running in prod."
No entries match this filter.