AWS EC2 – Get running instances only

AWS SDK has Console Sample project where you can see code populating number of your running Instances.

DescribeInstancesResponse ec2Response = ec2.DescribeInstances(request);
int numInstances = 0;
numInstances = ec2Response.Reservations.Count;
Console.WriteLine("You have " + numInstances + " Amazon EC2 instance(s) running.");

What you actually get is number of all your Instances, no matter if they are running or not.
If you want to get only running ones, query Reservations collection filtering by their State

DescribeInstancesRequest instanceRequest = new DescribeInstancesRequest();
List<Reservation> reservations = ec2.DescribeInstances(instanceRequest).Reservations;
List<Instance> runningInstances = reservations.Where(r => r.Instances.Any(i => i.State.Name == "running")).Select(r => r.Instances[0]).ToList();
numInstances = runningInstances.Count;

Leave a Reply

Your email address will not be published. Required fields are marked *