Google Cloud CLI commands

gcloud command lines for Google Cloud CLI 587.0.0, taken from Google's cheat sheet and from the SYNOPSIS and EXAMPLES sections of the command reference, grouped by task: setup, sign-in, configurations, projects, IAM, Compute Engine, GKE, Cloud Run, Cloud Storage, builds, Cloud SQL and logging. Names such as example-instance or my-bucket are sample values; words in capitals are placeholders. Rows that begin with a dash are flags. Alpha and beta commands and the remaining product groups are left out.

202 commands in 17 sections. Checked row by row against Google Cloud SDK documentation: The gcloud CLI cheat sheet on . Edited by Jay.

Setup, help and components 12

A gcloud command reads left to right as gcloud, an optional release level (alpha or beta), the component, the entity, the operation, then positional arguments and flags.

CommandWhat it does
gcloud initRun guided setupInteractive workflow that authorizes an account, picks or creates a configuration and sets its project, region and zone.
gcloud versionShow component versionsLists every installed component with its version number and says when updates exist.
gcloud infoShow environment detailsPrints the active account and project plus the directories where gcloud keeps its logs.
gcloud help -- projectSearch the help textFinds commands whose help mentions the words after the double dash; five results unless --limit raises it.
gcloud topic filtersRead the filter syntax guideSupplementary help page on the expressions the --filter flag accepts.
gcloud topic formatsRead the output format guideSupplementary help page on every format name and attribute that --format understands.
gcloud components listList CLI componentsShows each component's ID and whether it is installed, not installed or has an update waiting.
gcloud components install COMPONENT-1 COMPONENT-2Install componentsAdds the named components and their dependencies at the CLI version already in use, without upgrading anything.
gcloud components updateUpdate the CLIBrings every installed component to the newest release after listing the changes and asking for confirmation.
gcloud components remove COMPONENT-1 COMPONENT-2Remove componentsUninstalls the named components and anything depending on them, after a confirmation prompt.
gcloud feedbackSend feedback to GoogleLists the support channels and opens a browser on the one you pick.
gcloud surveyOpen the satisfaction surveyThe recurring survey prompt itself is switched off with the survey/disable_prompts property.

Sign-in and credentials 11

gcloud auth application-default login sets up credentials for client libraries only; it does not change the account that gcloud commands themselves run as.

CommandWhat it does
gcloud auth loginSign in with a user accountRuns a web sign-in and makes that account the active one in the current configuration.
gcloud auth login --no-browserSign in without a local browserFor a machine with no browser: authorization is finished with the gcloud CLI on a second machine that has one.
gcloud auth listList credentialed accountsShows every account with stored credentials and marks the single active one.
gcloud config set core/account [email protected]Switch the active accountMakes an account that already has stored credentials the one gcloud uses.
gcloud auth revokeRevoke stored credentialsWith no account named it logs out the active account; --all does the same for every account.
gcloud auth print-access-tokenPrint an access tokenUses the active account unless another account is named as an argument.
gcloud auth print-identity-tokenPrint an identity tokenAdd --audiences with a service URL to mint the token for that audience.
gcloud auth activate-service-account [email protected] --key-file=/path/key.json --project=PROJECT_IDSign in as a service accountImports the key file's credentials and activates them; the non-interactive counterpart of auth login.
gcloud auth application-default loginCreate Application Default CredentialsSaves user credentials where client libraries look for ADC, for running code locally without a service account.
gcloud auth application-default set-quota-project my-quota-projectSet the ADC quota projectRecords which project client libraries use for billing and quota; ADC must already exist.
gcloud auth application-default revokeRevoke Application Default CredentialsDeletes the local credential file made by application-default login; credentials set up another way are untouched.

Configurations and properties 12

CommandWhat it does
gcloud config set project PROJECT_IDSet the default projectStores the project in the active configuration, so later commands target it without --project.
gcloud config set compute/zone ZONE_NAMESet the default zoneCompute Engine commands then stop prompting for a zone when --zone is left out.
gcloud config set compute/region REGIONSet the default regionRegional Compute Engine commands then no longer ask for a region when --region is omitted.
gcloud config get projectPrint one propertyOutputs only the value held by the active configuration.
gcloud config unset projectClear a propertyRemoves it from the active configuration only, unless --installation is added.
gcloud config listList active propertiesShows the account, project and default region and zone that the active configuration sets.
gcloud config list --allList every propertyAlso prints the properties that have no value set.
--installationApply to all configurationsFlag of config set and config unset: the change covers the whole installation, not just the active configuration.
gcloud config configurations create my-configCreate a named configurationThe new configuration becomes active straight away unless --no-activate is added.
gcloud config configurations listList configurations
gcloud config configurations activate my-configSwitch configurationLater commands use that configuration's account, project and other properties.
gcloud config configurations delete my-configDelete a configurationRefuses the configuration that is active; activate another one first.

Projects, billing and APIs 10

CommandWhat it does
gcloud projects listList accessible projectsCovers active projects where the account is Owner, Editor, Browser or Viewer; deleted ones are left out.
gcloud projects describe example-foo-bar-1Show project metadataFails when the project does not exist or the account has no access to it.
gcloud projects create example-foo-bar-1 --name="Happy project" --labels=type=happyCreate a projectThe first argument is the new project ID; --name gives the display name and --labels attaches key=value pairs.
gcloud projects delete example-foo-bar-1Delete a projectNeeds the owner role or another role that holds resourcemanager.projects.delete.
gcloud projects add-iam-policy-binding example-project-id-1 --member='user:[email protected]' --role='roles/editor'Grant a role on a projectAdds one member and role pair to the project's policy; a condition can be attached with --condition.
gcloud projects remove-iam-policy-binding example-project-id-1 --member='user:[email protected]' --role='roles/editor'Revoke a role on a projectTakes the same member and role pair that was granted; --all also removes conditional copies.
gcloud billing projects link my-project --billing-account=0X0X0X-0X0X0X-0X0X0XLink a project to billingSets or replaces the billing account that accrues the project's charges.
gcloud services enable my-consumed-serviceEnable an APITurns the service on for the current project; --async returns without waiting, and several names can be listed.
gcloud services list --enabledList enabled APIsThis is what services list shows by default, written out explicitly.
gcloud services list --availableList APIs that can be enabled

IAM roles and service accounts 10

CommandWhat it does
gcloud iam service-accounts create some-account-name --display-name="My Service Account"Create a service accountLater IAM commands refer to the account by the email address this call returns.
gcloud iam service-accounts listList service accounts
gcloud iam service-accounts disable [email protected]Disable a service accountCredential generation and API requests made as the account fail until it is enabled again.
gcloud iam service-accounts delete [email protected]Delete a service account
gcloud iam service-accounts add-iam-policy-binding [email protected] --member='user:[email protected]' --role='roles/editor'Grant a role on a service accountGives the member that role over the service account itself, treated here as a resource.
gcloud iam service-accounts keys create key.json [email protected]Create a service account keyWrites the private part of the new key to the local file named first.
gcloud iam service-accounts keys list --iam-account=IAM_ACCOUNTList a service account's keys--managed-by=user narrows the list to user-managed keys and --created-before finds those due for rotation.
gcloud iam roles listList predefined rolesWith --project or --organization it lists that resource's custom roles instead.
gcloud iam roles create ProjectUpdater --organization=12345 --file=role_file_pathCreate a custom roleReads the definition from a YAML file; title, description and permissions can be passed as flags instead.
gcloud iam list-grantable-roles //cloudresourcemanager.googleapis.com/projects/PROJECT_IDList roles grantable on a resourceTakes the resource's full resource name or its URI.

Compute Engine instances 15

CommandWhat it does
gcloud compute instances listList VM instancesPrints every instance of the project as a table.
gcloud compute instances create example-instance --image-family=rhel-8 --image-project=rhel-cloud --zone=us-central1-aCreate a VM from an image familyBoots the newest image of the family; a public image also needs its --image-project.
--machine-type=MACHINE_TYPEChoose the machine typeFlag of instances create; n1-standard-1 is used when it is left out.
gcloud compute instances describe test-instanceShow all data of a VMAdd --format with a key list, such as yaml(name,status,disks), to print only those fields.
gcloud compute instances start example-instance --zone=us-central1-aStart a stopped VMWorks only on an instance that is currently stopped.
gcloud compute instances stop test-instanceStop a VMShuts the guest down cleanly; running it on a VM that is already stopped returns without an error.
gcloud compute instances stop test-instance --discard-local-ssd=TrueStop a VM that has Local SSDA VM with Local SSD disks needs the flag to say whether that data is discarded or preserved.
gcloud compute instances reset test-instanceHard-reset a VMThe guest operating system is not shut down cleanly first.
gcloud compute instances delete instance-1 --zone=us-central2-aDelete a VM--delete-disks and --keep-disks override the auto-delete setting of the attached disks.
gcloud compute instances set-machine-type example-instance --zone=us-central1-b --machine-type=n1-standard-4Change the machine typeThe VM has to be stopped (TERMINATED state) before its type can change.
gcloud compute instances add-tags test-instance --tags=tag-1,tag-2Add network tagsFirewall rules can then target the instance through these tags.
gcloud compute instances get-serial-port-output example-instance --zone=us-central1-bRead serial port outputSends what the VM wrote to its serial port to standard output, for diagnostics.
gcloud compute zones listList zones
gcloud compute machine-types listList machine typesCovers all zones unless a zone filter narrows it; obsolete types are hidden.
gcloud compute images listList boot imagesIncludes the public image projects such as debian-cloud and ubuntu-os-cloud next to the project's own images.

Disks, snapshots and networking 9

CommandWhat it does
gcloud compute disks create my-disk-1 my-disk-2 --zone=us-east1-aCreate persistent disksOne disk is made per name given, all in the stated zone.
gcloud compute disks resize example-disk-1 --size=6TBGrow a diskSize can only increase, and the disk may stay attached while it is resized.
gcloud compute disks snapshot test --zone=us-central1-a --snapshot-names=snapshot-test --description="This is an example snapshot"Snapshot a diskWorks even while the disk is attached to a running instance.
gcloud compute disks delete my-disk --zone=us-east1-aDelete a diskOnly possible when no instance has the disk attached.
gcloud compute snapshots listList snapshotsCombine with --filter, for example on creationTimestamp, to find snapshots older than a date.
gcloud compute firewall-rules create example-service --allow=tcp:8080 --description="Allow incoming traffic on TCP port 8080" --direction=INGRESSOpen a port with a firewall ruleAdd --source-ranges to restrict which address blocks may connect.
gcloud compute firewall-rules listList firewall rules
gcloud compute addresses create address-1 address-2 address-3 --region=us-central1Reserve IP addressesA reserved address stays with the project until it is released with addresses delete.
gcloud compute networks create network-nameCreate a VPC networkWithout flags the result is an auto subnet mode network with regional routing.

SSH and file copy 9

When the zone of the instance cannot be determined, compute ssh and compute scp ask for it; pass --zone to avoid the prompt.

CommandWhat it does
gcloud compute ssh example-instance --zone=us-central1-aSSH into a VMWraps ssh, taking care of authentication and of turning the instance name into an IP address.
gcloud compute ssh example-instance --zone=us-central1-a --command="ps -ejH"Run one command over SSHExecutes the quoted command on the VM and then exits instead of opening a shell.
--tunnel-through-iapConnect through IAPFlag of compute ssh and compute scp that routes the connection through Identity-Aware Proxy TCP forwarding.
--internal-ipUse the VM's internal addressFlag of compute ssh and compute scp for connecting from the same VPC, over VPN or across peered networks.
gcloud compute ssh VM_NAME --zone=ZONE --troubleshootDiagnose a failing SSH connectionTests areas such as VM status and network connectivity, then prints recommendations.
gcloud compute scp --recurse example-instance:~/narnia ~/wardrobeDownload a directory from a VMThe instance name and a colon prefix the remote path; --recurse copies the directory with its contents.
gcloud compute scp ~/localtest.txt ~/localtest2.txt example-instance:~/narniaUpload files to a VMSeveral local files may be listed; the last argument is the remote destination.
gcloud compute config-sshAdd VMs to the SSH configWrites a Host alias for each instance into ~/.ssh/config, so plain ssh can reach it; --remove undoes this.
gcloud compute start-iap-tunnel my-instance 3389 --local-host-port=localhost:3333Open an IAP TCP tunnelForwards the chosen local port to the instance port, here RDP, through Identity-Aware Proxy.

Kubernetes Engine clusters 12

CommandWhat it does
gcloud container clusters create sample-clusterCreate a GKE clusterUses the default configuration, which gives three nodes per zone unless --num-nodes says otherwise.
gcloud container clusters create-auto sample-clusterCreate an Autopilot cluster
gcloud container clusters listList clustersQueries every location unless --location, --region or --zone is given.
gcloud container clusters describe sample-clusterShow cluster details
gcloud container clusters get-credentials sample-cluster --location=us-central1-fPoint kubectl at a clusterWrites the cluster's credentials and endpoint into the kubeconfig file, HOME/.kube/config by default.
gcloud container clusters resize sample-cluster --num-nodes=2Resize a node poolActs on the single node pool; a cluster with several pools needs --node-pool to pick one.
gcloud container clusters update sample-cluster --enable-autoscalingTurn on node autoscalingApplies to the pool named by --node-pool, or to the default pool when none is named.
gcloud container clusters upgrade sample-cluster --node-pool=pool-1Upgrade a node poolMoves the pool to the Kubernetes version the cluster's control plane already runs.
gcloud container clusters upgrade sample-cluster --masterUpgrade the control planeWithout --cluster-version the target is the default cluster version.
gcloud container clusters delete sample-clusterDelete a clusterRemoves the control plane, every node instance and the Pods running on them.
gcloud container node-pools create node-pool-1 --cluster=sample-cluster --num-nodes=5Add a node poolThe pool appears in the cluster once all of its nodes are provisioned.
gcloud container node-pools list --cluster=sample-clusterList node pools

Cloud Run services and jobs 13

CommandWhat it does
gcloud run deployDeploy to Cloud RunCreates the service on first use and updates it afterwards; a missing service name is asked for.
gcloud run deploy my-backend --image=us-docker.pkg.dev/project/imageDeploy a container imageThe first argument is the service name and --image the container to run.
--source=SOURCEDeploy from source codeFlag of run deploy: builds with the Dockerfile in that directory when there is one, otherwise with Google Cloud buildpacks.
--allow-unauthenticatedMake the service publicFlag of run deploy; --no-allow-unauthenticated switches unauthenticated access off again.
gcloud run services listList services
gcloud run services describe SERVICEShow a service's detailsAdd --format=yaml for YAML, or --format=export for YAML without deployment-specific metadata and status.
gcloud run services update myservice --update-env-vars=KEY1=VALUE1,KEY2=VALUE2Change environment variablesSets the listed variables on an existing service.
gcloud run services update-traffic myservice --to-revisions=myservice-s5sxn=10,myservice-cp9kw=90Split traffic between revisionsEach revision name is followed by its percentage; one revision at 100 is a rollback.
gcloud run services update-traffic myservice --to-latestSend all traffic to the latest revisionKeeps following later revisions as they are deployed.
gcloud run services add-iam-policy-binding my-service --region='us-central1' --member='user:[email protected]' --role='roles/run.invoker'Let a user invoke a service
gcloud run services logs read my-serviceRead a service's logsGoes back one day by default; --log-filter and --limit narrow the result.
gcloud run services delete SERVICEDelete a service
gcloud run jobs execute my-jobRun a jobReturns as soon as the execution has started; --wait blocks until it has completed.

Functions and App Engine 14

CommandWhat it does
gcloud functions deploy NAMEDeploy a functionCreates the function, or updates the one that already has this name.
--runtime=RUNTIMEPick the function runtimeFlag of functions deploy: must be given the first time a function is deployed and may be omitted on later updates.
--trigger-httpGive the function an HTTP endpointFlag of functions deploy; the assigned endpoint is shown by functions describe.
gcloud functions listList functions--regions names the regions to look in; without it the functions/region property decides.
gcloud functions call helloWorld --data='{"message": "Hello World!"}'Call a function for testingHas a small fixed quota, so it is meant for testing and debugging rather than production.
gcloud functions logs readRead function logsShows 20 entries unless --limit changes it; a function name restricts the output to that function.
gcloud functions delete NAMEDelete a function
gcloud app create --region=us-centralCreate the App Engine appLeave the flag out to pick the region interactively.
gcloud app deploy ~/my_app/app.yamlDeploy an App Engine serviceUploads the code and configuration that the YAML file describes; files named in .gcloudignore are skipped.
--no-promoteDeploy without taking trafficFlag of app deploy: the new version is not promoted to receive all traffic.
gcloud app browseOpen the app in a browserAdd --service or --version to open something other than the default service.
gcloud app logs readRead recent app logsPrints the latest 200 entries from stdout, stderr and the crash log.
gcloud app versions listList deployed versionsCovers every service; --hide-no-traffic keeps only versions that receive traffic.
gcloud app versions delete v1Delete a versionA version that is currently receiving traffic cannot be deleted.

Cloud Storage 17

CommandWhat it does
gcloud storage lsList bucketsWith no path it prints the buckets of the default project.
gcloud storage ls gs://my-bucketList a bucket's contentsForward slashes in object names are presented as directories.
gcloud storage ls --recursive gs://bucketList everything recursivelyPrints a header and a block of lines for each subdirectory.
--long, -lShow size and creation timeFlag of storage ls, for objects only: adds the byte size and creation time to each URL.
gcloud storage cp *.txt gs://my-bucketUpload files
gcloud storage cp gs://my-bucket/*.txt .Download objects
gcloud storage cp --recursive dir gs://my-bucketUpload a directory tree
gcloud storage mv gs://my_bucket/oldprefix gs://my_bucket/newprefixRename objects under a prefixEvery object below the old prefix moves to the new one with the rest of its name unchanged.
gcloud storage rm gs://my-bucket/my-objectDelete an object
gcloud storage rm --recursive gs://my-bucket/Empty and delete a bucketRemoves every version of every object and then the bucket itself.
gcloud storage cat gs://bucket/*.txtPrint objects to stdoutAdd -r with a byte range, such as -r 256-939, to output only part of a file.
gcloud storage rsync data gs://my-bucket/data --recursiveSync a directory to a bucketCopies and updates objects so the destination matches the source; empty directory trees are not copied.
gcloud storage rsync gs://mybucket1 gs://mybucket2 --recursive --delete-unmatched-destination-objectsMirror one bucket to anotherThe extra flag also deletes destination objects that are missing from the source.
gcloud storage sign-url gs://my-bucket/file.txt --duration=10m --impersonate-service-account=sa@my-project.iam.gserviceaccount.comCreate a signed URLThe link embeds authentication, so someone without a Google account can use it until it expires.
gcloud storage buckets create gs://my-bucket --default-storage-class=nearline --location=asiaCreate a bucketThe location cannot be changed later; it is us when --location is left out.
gcloud storage buckets delete gs://my-bucketDelete a bucket
gcloud storage buckets add-iam-policy-binding gs://BUCKET --member=allUsers --role=roles/storage.objectViewerMake a bucket publicLets anyone read the objects in the bucket.

Builds and container images 13

CommandWhat it does
gcloud builds submit "gs://bucket/object.zip" --tag=gcr.io/my-project/imageBuild an image from a DockerfileCloud Build runs a remote docker build on the source and tags the result; the tag must be in gcr.io or pkg.dev.
gcloud builds submit "gs://bucket/object.zip" --config=config.yamlBuild with a config fileUses the named YAML or JSON build configuration; cloudbuild.yaml is the default name.
gcloud builds listList buildsReturns at most 50 builds unless --limit changes it; --ongoing keeps only those in QUEUED or WORKING status.
gcloud builds log BUILDShow a build's logAdd --stream to follow a build that is still in progress.
gcloud builds cancel '123-456-789'Cancel a running buildSeveral build IDs can be given to cancel them together.
gcloud artifacts repositories create my-repo --repository-format=dockerCreate a Docker repositoryUses the project and location set as defaults; --repository-format is required.
gcloud artifacts repositories listList repositories--limit caps how many repositories are returned.
gcloud artifacts repositories delete my-repoDelete a repositoryPoint anything that still depends on the repository at a new location first.
gcloud artifacts docker images list us-central1-docker.pkg.dev/my-project/my-repoList images in a repositoryAdd --include-tags to show the tags of each image as well.
gcloud artifacts docker images delete us-west1-docker.pkg.dev/my-project/my-repository/busy-boxDelete an imageEvery digest and tag of the image goes with it.
gcloud auth configure-dockerRegister the Docker credential helperAdds gcloud as credHelper to Docker's configuration file, overwriting an existing credHelper entry.
gcloud container images list-tags gcr.io/myproject/myimageList image tags and digestsFor images hosted on Container Registry.
gcloud dockerDocker access (deprecated)Deprecated wrapper; the reference names gcloud auth configure-docker as the replacement.

Cloud SQL 12

CommandWhat it does
gcloud sql instances create prod-instance --database-version=POSTGRES_15 --cpu=2 --memory=8GiB --zone=us-central1-a --root-password=password123Create a PostgreSQL instanceMYSQL_8_0 is the engine used when --database-version is left out.
gcloud sql instances listList SQL instancesInstances come back in alphabetical order of their names.
gcloud sql instances describe INSTANCEShow instance configurationIncludes the IP address, region and CA certificate.
gcloud sql instances patch INSTANCEChange instance settingsFollowed by the setting flags to change, for example --tier for the machine type.
gcloud sql instances delete INSTANCEDelete an instanceAdd --enable-final-backup to have a last backup taken at the moment of deletion.
gcloud sql connect my-instance --user=rootConnect to an instance--user picks the database user and --database the PostgreSQL or SQL Server database.
gcloud sql databases create DATABASE --instance=INSTANCECreate a database
gcloud sql users create USERNAME --instance=INSTANCECreate a database userHost, type and password of the user are set with further flags such as --password.
gcloud sql users set-password USERNAME --instance=INSTANCEChange a user's passwordAdd --prompt-for-password to type the password with echo off rather than passing --password.
gcloud sql backups create --instance=INSTANCEBack up an instance
gcloud sql export sql INSTANCE URIExport a SQL dump to a bucketURI is a gs:// path; the export fails if the file exists, and a .gz ending compresses it.
gcloud sql import sql test-instance-1 gs://test-bucket/test-file.sql.gz --database=testdbImport a SQL dumpReads the dump file from Cloud Storage into the named database.

Logging and secrets 8

CommandWhat it does
gcloud logging read "resource.type=gce_instance"Read log entries by filterReturns matching entries newest first; only the last day is searched unless --freshness widens it.
gcloud logging read "severity>=ERROR"Read errors and worse
gcloud logging logs listList log namesOnly logs that actually hold entries are shown.
gcloud logging write LOG_NAME "A simple entry"Write a test log entryCreates the log when it does not exist; meant for simple testing, not for regular log shipping.
gcloud secrets create my-secret --data-file=/tmp/secretCreate a secret from a fileReturns an error when a secret of that name already exists.
gcloud secrets versions add my-secret --data-file=/tmp/secretAdd a secret versionThe secret itself must already exist.
gcloud secrets versions access 123 --secret=my-secretRead a secret valueOutput is UTF-8 formatted, which can corrupt binary secrets; --out-file writes the raw bytes.
gcloud kms decrypt --key=frodo --keyring=fellowship --location=global --ciphertext-file=path/to/input/ciphertext --plaintext-file=path/to/output/plaintext.decDecrypt a file with a KMS keyWrites the result to the plaintext file; '-' as the file name sends it to stdout.

Global flags 14

CommandWhat it does
--project=PROJECT_IDTarget another project onceReplaces the configured project for one invocation, both as the home of the resource and for quota and billing.
--account=ACCOUNTRun as another account onceTakes precedence over the core/account property for this invocation only.
--configuration=CONFIGURATIONUse a named configuration onceSetting CLOUDSDK_ACTIVE_CONFIG_NAME in the environment does the same for a whole terminal session.
--impersonate-service-account=SERVICE_ACCOUNT_EMAILSAct as a service accountEvery API request of the command is made as that account, with no key file; a comma-separated list forms a delegation chain.
--billing-project=BILLING_PROJECTCharge quota to another projectFor working on one project while a different one pays the quota; wins over billing/quota_project.
--quiet, -qDisable interactive promptsDefaults are used where input is needed, or an error is raised; the usual choice for scripts.
--verbosity=VERBOSITYSet the message levelOne of debug, info, warning, error, critical or none; warning is the default.
--log-httpLog HTTP requests and responsesEverything gcloud sends to and receives from the server is written to stderr.
--flags-file=YAML_FILERead flags from a fileA YAML or JSON dictionary of flag names and values, handy for values full of special characters.
--helpShow detailed helpWorks after any command or group, for example gcloud topic --help.
-hShow summary helpPrints a short usage summary instead of the full help page.
--version, -vPrint version and exitAccepted only directly after gcloud, not on subcommands.
--trace-token=TRACE_TOKENAttach a trace tokenRoutes traces of the service requests so an issue can be investigated.
--user-output-enabledToggle console outputUse the --no-user-output-enabled form to silence the output meant for the user.

Filtering and formatting output 11

When several output flags are combined they are applied in a fixed order: --flatten, then --sort-by, then --filter, then --limit.

CommandWhat it does
--format=FORMATChoose the output formatCommon values are json, yaml, csv, table and value; gcloud topic formats documents all of them.
--filter=EXPRESSIONFilter listed resourcesFlag of list commands: only items for which the Boolean expression is true are shown.
--limit=LIMITCap the number of resultsFlag of list commands; applied after --flatten, --sort-by and --filter.
--sort-by=[FIELD,...]Sort the resultsFlag of list commands: ascending by default, a ~ before a field name reverses it.
--flatten=[KEY,...]Expand lists into recordsA record holding a list of N items in KEY becomes N separate records, which --format and --filter then see.
gcloud compute instances list --filter="zone ~ ^us AND -machineType:f1-micro"Filter with a regular expressionKeeps instances whose zone starts with us and drops the f1-micro machine type.
gcloud compute instances list --filter="labels.my-label:*" --limit=10Filter by labelMatches instances carrying the label whatever its value, and stops after ten.
gcloud projects list --format="table(projectNumber,projectId,createTime.date(tz=LOCAL))" --filter="createTime>=2018-01-15T12:00:00" --sort-by=createTimeBuild a custom tablePrints three chosen columns, with creation times in the local time zone, for projects made since the date, oldest first.
gcloud info --format="value(config.account)"Print one value for scriptsThe value format outputs just the selected key, here the signed-in account.
gcloud container images list-tags gcr.io/myproject/myimage --format=jsonGet full JSON outputJSON shows everything the table view shortens, such as the untruncated digests.
gcloud compute project-info describe --flatten="quotas[]" --format="csv(quotas.metric,quotas.limit,quotas.usage)"Flatten a list into CSV rowsEach quota of the project becomes one CSV line with its metric, limit and usage.

Notes

The five-minute setup

gcloud auth login runs a web sign-in and makes that account the active one, and gcloud config set project PROJECT_ID stores the project that later commands target. gcloud init walks through both and can also set a default Compute Engine region and zone, and gcloud info prints the active account, project and log paths when something points at the wrong place. For a single command the stored project is overridden with --project=PROJECT_ID.

Flags that change output

--format=FORMAT reshapes the output of any command (json, yaml, a table with chosen columns, a single value), so scripts do not have to parse the default table. --flatten=[KEY,...] turns a list inside a resource into one record per item, which pairs well with a table or CSV format. --quiet, -q disables interactive prompts: defaults are used, or an error is raised when input is required, so it belongs in automation. --flags-file=YAML_FILE loads flags from a YAML or JSON file, which keeps a long deploy command reviewable.

Debugging a command

--log-http writes the underlying HTTP requests and responses to stderr, which shows exactly what a command sent when the error message is opaque. --configuration=CONFIGURATION runs one command with a named configuration without switching the active one. Commands that exist only at the alpha or beta release level are written with that word after gcloud. gcloud help -- project searches the built-in help text for a term, which is often quicker than the web reference.

Questions

How do I switch projects?

gcloud config set project PROJECT_ID changes the default in the active configuration. For one command, add --project=PROJECT_ID.

How do I get JSON from a gcloud command?

Set --format=FORMAT to json, as in gcloud container images list-tags gcr.io/myproject/myimage --format=json. The value format prints a single field, as in gcloud info --format="value(config.account)", which is convenient in shell scripts.

How do I run gcloud in a script without prompts?

Add --quiet, -q (either form). Where input is required the default is used, or an error is raised.

How do I see what API calls a command makes?

Add --log-http. The HTTP requests and responses are written to stderr.

Sources and checks

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

129 rows from the earlier version of this page were removed in that check: duplicates, and bindings the documentation does not list or lists differently.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.