Reputation: 1292
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
Upvotes: 2
Views: 3196
Reputation: 3404
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)
Upvotes: 10