Wednesday, August 29, 2012

Using the AWS .NET SDK to look up an EC2 instance's IP address

I found a lot of documentation about the AWS API, and a lot of documentation about the AWS .NET SDK, but nothing that put together all the pieces required to actually write a working C# program that calls the AWS .NET SDK to do real work. In particular, the syntax to filter a list of instances, and to access the properties of an instance, wasn't easy to guess. I have written such a program. It looks up an EC2 instance based on its public IP address, and outputs the instance's private IP address. You could easily modify this to do the lookup based on other filter criteria, and to output additional properties of the instance. Of course you might want to add some nicer error handling and user interface code. Start by creating a C# Windows Console App. I happen to have used Visual Studio 2010 Professional. Using Nuget, search online and add the package "AWS SDK for .NET". I also found it necessary to explicitly add a reference to System.Configuration. Then you'll just need to create two files, app.config and program.js. App.config should look like this, substituting your own AWS access key and AWS secret key: Program.cs should look like this: /* Takes the public IP address of an AWS EC2 instance as an argument. Outputs that instance's private IP address. Assumes there is exactly one instance with the given public IP address. Be sure to specify your own AWS access key and secret key in app.config. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Collections.Specialized; using Amazon; using Amazon.EC2; using Amazon.EC2.Model; namespace AwsGetInstanceIP { class Program { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Must specify public IP address"); return; } NameValueCollection appConfig = ConfigurationManager.AppSettings; AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client( appConfig["AWSAccessKey"], appConfig["AWSSecretKey"], RegionEndpoint.USEast1 // change if your instances are in an AWS region other than us-east ); DescribeInstancesRequest request = new DescribeInstancesRequest(); Filter filter = new Filter(); filter.WithName("ip-address"); filter.WithValue(args[0]); request.Filter.Add(filter); DescribeInstancesResponse ec2Response = ec2.DescribeInstances(request); int numReservations = ec2Response.DescribeInstancesResult.Reservation.Count; if (numReservations != 1) { Console.WriteLine("Expecting exactly 1 reservation, but found " + numReservations); return; } int numInstances = ec2Response.DescribeInstancesResult.Reservation[0].RunningInstance.Count; if (numInstances != 1) { Console.WriteLine("Expecting exactly 1 instance, but found " + numInstances); return; } string privateIpAddress = ec2Response.DescribeInstancesResult.Reservation[0].RunningInstance[0].PrivateIpAddress; Console.WriteLine(privateIpAddress); } } }