Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcloud compute command to know current zone of machine

Tags:

cloud

gcloud

zone

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.

like image 466
Bharat Karale Avatar asked Feb 22 '16 05:02

Bharat Karale


4 Answers

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.

like image 138
Jeffrey Vaughan Avatar answered Nov 02 '22 16:11

Jeffrey Vaughan


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

gcloud compute instances list --filter="name=('`hostname`')" --format 'csv[no-heading](zone)'
like image 21
Jay Jungalwala Avatar answered Nov 02 '22 16:11

Jay Jungalwala


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
like image 1
Dave_J Avatar answered Nov 02 '22 16:11

Dave_J


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
like image 1
Brandon Yarbrough Avatar answered Nov 02 '22 16:11

Brandon Yarbrough