gcloud compute command to know current zone of machine
Asked Answered
F

4

9

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.

Foxed answered 22/2, 2016 at 5:44 Comment(0)
N
14

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.

Nicotiana answered 22/2, 2016 at 15:12 Comment(2)
list name is deprecated and --format may be simplified: gcloud compute instances list --filter="name=('your-hostname')" --format "value(zone)"Discant
tks @xmedeko, the --format "value(zone)" is very usefulAdapa
G
4

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

gcloud compute instances list --filter="name=('`hostname`')" --format 'csv[no-heading](zone)'
Garfieldgarfinkel answered 29/1, 2021 at 14:53 Comment(0)
E
1

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
Envious answered 27/6, 2018 at 10:45 Comment(0)
E
1

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
Execratory answered 19/8, 2022 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.