Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@samkeen
Last active January 23, 2024 17:07
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save samkeen/4255e1c8620be643d692 to your computer and use it in GitHub Desktop.
Save samkeen/4255e1c8620be643d692 to your computer and use it in GitHub Desktop.
Get the subnet and VPC id of a running EC2 instance

First get the Interface mac address, then use that to run the full command

INTERFACE=$(curl --silent http://169.254.169.254/latest/meta-data/network/interfaces/macs/)
SUBNET_ID=$(curl --silent http://169.254.169.254/latest/meta-data/network/interfaces/macs/${INTERFACE}/subnet-id)
VPC_ID=$(curl --silent http://169.254.169.254/latest/meta-data/network/interfaces/macs/${INTERFACE}/vpc-id)

echo SUBNET_ID

Not sure this will work if you have more than one network interface

@matthewmrichter
Copy link

Heads up, you missed a dollar sign on your echo statement

@jtanton
Copy link

jtanton commented Aug 3, 2018

Thanks this help me. Here is the powershell version to get the VPC_ID.
$INTERFACE=$(Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/network/interfaces/macs/)
$SUBNET_ID=$(Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/network/interfaces/macs/$INTERFACE/subnet-id)
$VPC_ID=$(Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/network/interfaces/macs/$INTERFACE/vpc-id)
$VPC_ID.content

@akhon
Copy link

akhon commented May 11, 2021

Not sure this will work if you have more than one network interface

this is when you have multiple interfaces
INTERFACE=$(curl --silent http://169.254.169.254/latest/meta-data/network/interfaces/macs/ | head -n1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment