Skip to content
Advertisement

List the number of running instances in an AWS region

I want to list the number of all running ec2 instances in the us-west-2 region and I was able to list the instances but actually, I want the number of instance names is not nessosry. please see that below code

import boto3
ec2client = boto3.client('ec2',region_name='us-west-2')
response = ec2client.describe_instances()
for reservation in response["Reservations"]:
    for instance in reservation["Instances"]:
        if instance['State']['Name'] == 'running':
           x = (instance["InstanceId"])
           print (x)

Output is here

enter image description here

Output type

enter image description here

Advertisement

Answer

You can store those names in a list, and check the list length:

running_instances = []

ec2client = boto3.client('ec2',region_name='us-west-2')
response = ec2client.describe_instances()
for reservation in response["Reservations"]:
    for instance in reservation["Instances"]:
        if instance['State']['Name'] == 'running':
           x = (instance["InstanceId"])
           #print(x)
           running_instances.append(x)
        
print('Number of running instances', len(running_instances))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement