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

How to get the total count of Instances and volumes and loadbalancers present in the aws using 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)

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

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 基本上就是计数。