Search code examples
c#.netamazon-web-servicesamazon-ec2cloud

Amazon EC2 .NET API, launch random instance


I have the following question...I wonder if there is some methods on the EC2 .NET API that allow me to list all the available AMIs(like in the web interface) in a given region. At least their id's. I want to set up a random image and this is the only missed piece from the puzzle.


Solution

  • It should be simple. Here is a code excerpt that will return all AMIs in the available or pending state (add your own filters and surrounding try/catch block):

    AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(
        "YOUR_ACCESS_KEY",
        "YOUR_SECRET_KEY"
        );
    
    DescribeImagesRequest request = new DescribeImagesRequest();
    request.WithFilter(new Filter[] {
        new Filter().WithName("state").WithValue("available", "pending")});
    DescribeImagesResponse ec2Response = ec2.DescribeImages(request);
    

    This query will bring all public AND private AMIs. Since the results in the result set contain the attribute which says whether an instance is public or private (e.g. <Visibility>Private</Visibility>).

    If you want only your own AMIs, add the .WithOwner("YOUR_AMAZON_ID") to your filter definition. For example:

    request.WithFilter(new Filter[] {
        new Filter().WithName("state").WithValue("available", pending")})
        .WithOwner("YOUR_AMAZON_ID");
    

    or

    request.WithOwner("YOUR_AMAZON_ID");  
    

    For further reference, please see the AWS SDK for .NET Documentation. On the tree on the left, select Amazon/Amazon.EC2.Model/DescribeImagesRequest Class. Also, the DescribeImages API Reference contains the name and possible values of every Filter you can use in this request.

    PS: Since you are explicitly talking about regions, and AMIs do not have a region associated to them, it might be possible that you are talking about Instances instead. In this case, there is a similar request called DescribeInstances. Find more details about it here (Amazon/Amazon.EC2.Model/DescribeInstancesRequest Class) and here.

    Hope it helps.