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
JavaScript
x
9
1
import boto3
2
ec2client = boto3.client('ec2',region_name='us-west-2')
3
response = ec2client.describe_instances()
4
for reservation in response["Reservations"]:
5
for instance in reservation["Instances"]:
6
if instance['State']['Name'] == 'running':
7
x = (instance["InstanceId"])
8
print (x)
9
Output is here
Output type
Advertisement
Answer
You can store those names in a list, and check the list length:
JavaScript
1
13
13
1
running_instances = []
2
3
ec2client = boto3.client('ec2',region_name='us-west-2')
4
response = ec2client.describe_instances()
5
for reservation in response["Reservations"]:
6
for instance in reservation["Instances"]:
7
if instance['State']['Name'] == 'running':
8
x = (instance["InstanceId"])
9
#print(x)
10
running_instances.append(x)
11
12
print('Number of running instances', len(running_instances))
13