Skip to content

Instantly share code, notes, and snippets.

@ngrogg
Created March 27, 2024 12:51
Show Gist options
  • Save ngrogg/32fd93c09eb6e1a79ed48d243c9bb934 to your computer and use it in GitHub Desktop.
Save ngrogg/32fd93c09eb6e1a79ed48d243c9bb934 to your computer and use it in GitHub Desktop.
Some Useful Google Cloud CLI Commands

Some Useful Google Cloud CLI Commands

If not done already, configure Google Cloud CLI.
Instructions below assume DEB based distro like Debian or Ubuntu.
Instructions from Google Cloud SDK Docs

Pre-requisities to install Google CLI (skip if already done)
Add GPG key,
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo gpg --dearmor -o /usr/share/keyrings/cloud.google.gpg

Create .deb,
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list

Install Google Cloud CLI,
sudo apt update && sudo apt install google-cloud-cli

Initialize connection,
gcloud init

Log in using Google account,
gcloud auth login

Set default project (optional),
gcloud config set project PROJECT

Get list of projects,
gcloud projects list

List all VMs in project,
gcloud compute instances list --project PROJECT

Use grep to find a specifc VM
gcloud compute instances list --project PROJECT | grep HOSTNAME

List all VMs in project w/ partial matching,
gcloud compute instances list --project $(gcloud projects list | grep PROJECT | awk '{print $1}')

This can have problems if there are similarly named projects ex.
project1-qat
project1-staging
project1-production

This can be alleviated with arrays and such if desired, but is better suited for a script than a one liner.

Connect to Linux server via SSH using gcloud,
gcloud compute ssh SERVER --zone ZONE --project PROJECT --tunnel-through-iap

Output Google Cloud Serial Console logs:
gcloud compute instances tail-serial-port-output SERVER --zone ZONE --project PROJECT

Similar to viewing server syslog/messages. Very useful if a server is non-responsive to SSH.

Stop/Start server,
gcloud compute instances stop SERVER --zone ZONE --project PROJECT
gcloud compute instances start SERVER --zone ZONE --project PROJECT

View disks in project,
gcloud compute disks list --project PROJECT

Use grep to search for a specific disk like a hostname,
gcloud compute disks list --project PROJECT | grep CRITERIA

View snapshot policies for disks,
gcloud compute disks list --project PROJECT --format text | grep -E 'name|resourcePolicies'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment