Skip to content

Instantly share code, notes, and snippets.

@samkeen
Last active January 23, 2024 17:07
Show Gist options
  • Select an option

  • Save samkeen/4255e1c8620be643d692 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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

@jtanton
Copy link
Copy Markdown

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
Copy Markdown

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