Thursday, March 17, 2022

[SOLVED] Powershell get region from AWS metadata

Issue

I have an EC2 instance and I am running a Powershell script there where I would like to get the region that the EC2 is running in.

Currently I have workaround like this which grabs the availability zone first. The availability zone is in the format like 'us-east-1a'.

$region = invoke-restmethod -uri http://169.254.169.254/latest/meta-data/placement/availability-zone 
if ($region -like "*east*") {$region = "us-east-1"} ELSE {$region = "us-west-2"} 

I would like to just grab the region, rather than get the availability zone and then do some modifications. I know there is a possibility to use:

http://169.254.169.254/latest/dynamic/instance-identity/document

This returns a JSON object which has the region, but I would also need to parse the JSON to achieve this.

How do I get just the region?


Solution

Will this work?

PS C:\> $region = invoke-restmethod -uri http://169.254.169.254/latest/meta-data/placement/availability-zone

PS C:\> $region.Substring(0,$region.Length-1)


Answered By - helloV
Answer Checked By - Robin (WPSolving Admin)