Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell get region from AWS metadata

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?

like image 260
William Ross Avatar asked Aug 22 '17 17:08

William Ross


People also ask

How do I find the region of an EC2 instance?

retrieve-EC2-region-information-from-metadata.md Sometimes you want to retrieve EC2 insntances' region information. You can query that information through instance metadata(169.254. 169.254). Response's JSON has a region key, so if you just want to get region, filter the key with jq .

How do I change the region in AWS PowerShell?

There are two ways to specify the AWS Region to use when running AWS Tools for PowerShell commands: Use the -Region common parameter on individual commands. Use the Set-DefaultAWSRegion command to set a default Region for all commands.

Which PowerShell cmdlet provides information about EC2 instances?

EC2: Get-EC2InstanceMetadata Cmdlet | AWS Tools for PowerShell.

Which PowerShell cmdlet is used to tag AWS resources?

EC2: New-EC2Tag Cmdlet | AWS Tools for PowerShell.


1 Answers

You can use ConvertFrom-Json :

PS C:\> $region = (Invoke-WebRequest -UseBasicParsing -Uri http://169.254.169.254/latest/dynamic/instance-identity/document | ConvertFrom-Json | Select region).region

edit: added -UseBasicParsing

like image 94
Davide DG Avatar answered Oct 04 '22 04:10

Davide DG