Bharat Karale
Bharat Karale

Reputation: 101

gcloud compute command to know current zone of machine

I need help in google cloud , I am doing 1 application using google cloud. in google cloud I have 1 instance of windows and google cloud sdk on that. I need one command which will return zone name of that instance. Note - I don't need zone list. I need only that zone name where my instance is running. thank you in advance.

Upvotes: 9

Views: 13355

Answers (4)

Brandon Yarbrough
Brandon Yarbrough

Reputation: 38399

Assuming you have some sort of URL-fetching tool like cURL, you can get the zone name like this:

curl http://metadata.google.internal/computeMetadata/v1/instance/zone -H Metadata-Flavor:Google | cut '-d/' -f4

Upvotes: 1

Jay Jungalwala
Jay Jungalwala

Reputation: 71

If on the instance itself and you want to get the zone:

gcloud compute instances list --filter="name=('`hostname`')" --format 'csv[no-heading](zone)'

Upvotes: 4

Dave_J
Dave_J

Reputation: 408

Jeffrey's answer is spot on for using the gcloud command line tool. If you'd rather use the GoogleCloud PowerShell module, the following will get you the uri of the zone:

$zone = (Get-GCEInstance).Where({$_.Name -eq $(hostname)}).Zone

e.g. this might populate $zone with:

https://www.googleapis.com/compute/v1/projects/my-project-001/zones/us-east1-a

If you just need the end section (and annoyingly, parameters on other cmdlets seem to require only the end section and the uri is not a valid format), you can do:

$zone.Substring($zone.LastIndexOf("/")+1)

to return:

us-east1-a

Upvotes: 1

Jeffrey Vaughan
Jeffrey Vaughan

Reputation: 894

tl;dr:

gcloud compute instances list <your instance name> --format 'csv[no-heading](zone)'

. . .

This is doing two things. The

gcloud compute instances list your-instance-name

part lists all instances with that name, e.g.

NAME                ZONE           MACHINE_TYPE  PREEMPTIBLE INTERNAL_IP    EXTERNAL_IP    STATUS
your-instance-name  europe-west1-c n1-standard-1             1.000.000.001 100.000.000.01 RUNNING

And the

--format 'csv[no-heading](zone)'  

part reformats the output to be a table with with headers and only the zone column. See https://cloud.google.com/sdk/gcloud/reference/topic/formats (or gcloud help topic formats) for more information about formatting output.

Upvotes: 14

Related Questions