简体   繁体   中英

How can I list all EC2 instances using Amazon .NET library?

I'm trying to programatically access all of my EC2 instances using the .NET library .

How can I get a list of all instances, and fetch their individual IP address?

Use AmazonEC2Client.DescribeInstances Method

result = client.DescribeInstances();

foreach (var instance in result.Reservations[0].Instances) {
    privateIps.add(instance.PrivateIpAddress);
}

In AWS and EC2 Speak, when you want to get a list of something, or find out more about it, it's a "Describe" call.

For example:

... and the one you're specifically looking for:

The DescribeInstances call will return you a data structure that has the IP Address for each instance. Note that this is a PAGED API, which means if you many instances (>1000) you'll need to keep calling it, providing the relevant page token, to get the complete list.

Here is the sample code through which will get you the list of InstanceIDs:

_client = new AmazonEC2Client(awsAccessKeyId, awsSecretAccessKey, RegionEndpoint.USEast2);
        bool done = false;
        var InstanceIds = new List<string>();
        DescribeInstancesRequest request = new DescribeInstancesRequest();
        while (!done)
        {
            DescribeInstancesResponse response = await _client.DescribeInstancesAsync(request);

            foreach ( Reservation reservation in response.Reservations)
            {
                foreach (Instance instance in reservation.Instances)
                {
                    InstanceIds.Add(instance.InstanceId);
                }
            }

            request.NextToken= response.NextToken;

            if (response.NextToken == null)
            {
                done = true;
            }
        }

You can replace instance.InstanceId with instance.PublicIpAddress to get the list of IP addresses. Hope this helps!

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