如何使用 boto3 获取 aws 中存在的实例、卷和负载均衡器的总数?

dow*_*dow 5 python boto amazon-web-services boto3

我需要使用 boto3 从 aws 控制台获取总计数 我尝试显示实例和卷列表,但不显示计数。

我想知道如何列出所有存在的资源和计数。

任何人都可以指导我吗?

 for region in ec2_regions:
 conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,
               region_name=region)
instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running','stopped']}])

for instance in instances:
    #if instance.state["Name"] == "running":
        print (instance.id, instance.instance_type, region)


volumes = conn.volumes.filter()

for vol in volumes:
    print(vol.id,vol.volume_type,region,vol.size)
Run Code Online (Sandbox Code Playgroud)

我想获取每个资源的总数。我尝试使用 len、size 和其他可用键来获取计数,但没有成功。

bim*_*api 4

返回的对象filter()是类型的boto3.resources.collection.ec2.instancesCollection,并且没有函数需要__len__的方法len()。我想到了几种不同的解决方案:

  • 从集合中创建一个列表并使用它。例如,my_list = [instance for instance in instances]; len(my_list)。这就是我通常做的事情。
  • 使用该enumerate函数,起始值为 1。例如,for i, instance in enumerate(instances, start=1): pass。最后一次迭代之后,i本质上就是计数。