I have the following bash script to retrieve instance metadata (IMDSv2) on Linux server:
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>&1 null)
instance_id=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/instance-id)
which is referred from the AWS documentation site here. However, it does not have information for Windows EC2 instances using power shell cmd.
What is the equivalent IMDSv2 cmd for EC2 on Windows Server?
In order to use the above IMDSv2 on Windows EC2 server, use the following cmd:
$token = Invoke-RestMethod -Method Put -Uri http://169.254.169.254/latest/api/token -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"}
$instance_id = Invoke-RestMethod -Method Get -Uri http://169.254.169.254/latest/meta-data/instance-id -Headers @{"X-aws-ec2-metadata-token" = $token}
Write-Host "Instance ID: $instance_id"
This will print the output as: Instance ID: i-0fe2f8ed980984