Reputation: 119
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
Output type
Upvotes: 1
Views: 1992
Reputation: 238209
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))
Upvotes: 4
Reputation: 269360
You can use a filter to identify running instances.
Using the Resource method:
import boto3
ec2_resource = boto3.resource('ec2')
instances = ec2_resource.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
# List running instances
for instance in instances:
print(instance.instance_id)
# Count running instances
count = len(list(instances))
print(f"{count} instances running")
Using the Client method:
import boto3
ec2_client = boto3.client('ec2')
response = ec2_client.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
# List running instances
count = 0
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
print(instance["InstanceId"])
count += 1
# Count running instances
print(f"{count} instances running")
Upvotes: 1