列出 AWS 区域中 运行 个实例的数量

List the number of running instances in an AWS region

我想列出 us-west-2 区域中所有 运行 ec2 实例的数量,我能够列出这些实例,但实际上,我希望实例名称的数量不是 nessosry。请看下面的代码

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)

输出在这里

输出类型

您可以将这些名称存储在列表中,并检查列表长度:

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))

您可以使用 过滤器 来识别 运行 个实例。

使用资源方法:

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")

使用客户端方法:

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")