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?
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 .
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.
EC2: Get-EC2InstanceMetadata Cmdlet | AWS Tools for PowerShell.
EC2: New-EC2Tag Cmdlet | AWS Tools for PowerShell.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With