简体   繁体   中英

How to get the VPC Id of an EC2 instance?

I need to identify the VpcId for the current EC2 instance using the C# AWS SDK. I have been trying to do this for a couple of hours now with no real luck.

My current approach is something like this,

var currentInstanceId = Amazon.EC2.Util.EC2Metadata.InstanceId; // Get Current Instance Id

AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey);
var ec2Client = AWSClientFactory.CreateAmazonEC2Client(creds, clientRegionEndpoint);
var instances = ec2Client.DescribeInstances();

foreach (var reservation in instances.Reservations)
{
  foreach (var instance in reservation.Instances)
  {
    if (instance.InstanceId.Equals(currentInstanceId)) // Compare Instance Id with all available instances 
      return instance.VpcId;
  }
}

I feel like there should be an easier way to do this. Any help on this would be really appreciated.


Update:

With @jbird's help I was able to achieve this using,

Amazon.EC2.Util.EC2Metadata.NetworkInterfaces.First().VpcId

Under Amazon.EC2.Util.EC2Metadata look under NetworkInterfaces . Each network interface has a VpcId .

This gets the VPC ID from the EC2 instance's metadata at http://169.254.169.254/latest/meta-data/network/interfaces/macs/${mac}/vpc-id . ( Reference )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM