Search code examples
pythonaws-sdkaws-cliboto3aws-security-group

aws python boto3 is not returning the right number of security groups


I am using Python SDK boto3 in order to get all the security groups into the region but I am getting the wrong number. there is my code:

## Client connection
ec2 = boto3.client(
    'ec2',
    aws_access_key_id=aws_access_key,
    aws_secret_access_key=aws_secret_key,
    region_name = ec2_region_name
)


def lambda_handler(event, context):
    count = 0
    for sg in ec2.describe_security_groups():
        count = count + 1
    print(count)

The result is 2 when there are hundreds of security groups.

What am I doing wrong?


Solution

  • Please check describe_security_groups documentation return value again.

    You need to read the list from the return dictionary key ["SecurityGroups"]

     for sg in ec2.describe_security_groups()["SecurityGroups"]:
            count = count + 1
        print(count)