Search code examples
pythonamazon-web-servicesboto3boto

How to get the total count of Instances and volumes and loadbalancers present in the aws using boto3?


I need to get the total counts from aws console using boto3 I tried to display instances and volumes list but not counts.

I want to know how to list all resources present with the counts.

Can anyone please guide me on this.

 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)

I want to get the Total count of each resource. I tried len, size, and other available keys for getting the count but in vain.


Solution

  • The objects returned by filter() are of type boto3.resources.collection.ec2.instancesCollection and don't have the __len__ method that the len() function needs. Couple of different solutions come to mind:

    • Create a list from the collection, and use that. E.g., my_list = [instance for instance in instances]; len(my_list). This is what I typically do.
    • Use the enumerate function, with a start value of 1. E.g., for i, instance in enumerate(instances, start=1): pass. After the last iteration, i will essentially be the count.