devxvda1
devxvda1

Reputation: 462

Always getting KeyError when trying to access the key in a dictionary

I'm writing a Python script using the Boto3 of AWS to manage the security groups. I created a dictionary to get the group ID and its properties only. I could access the properties of sg-aaaaaaaa but when I was trying to access the sg-bbbbbbbb, it always throws a KeyError.

How I Created the Dictionary

def get_rules(sg_ids, region):
    sg_rules = {}
    sg_rules['SecurityGroups'] = []
    ec2 = boto3.client('ec2', region_name=region)

    for sg_id in sg_ids:
        response = ec2.describe_security_groups(
            Filters=[
                {
                    'Name': 'group-id',
                    'Values': [
                        sg_id
                    ]
                }
            ]
        )
        data = response['SecurityGroups'][0]['IpPermissions']

        sg_rules['SecurityGroups'].append({sg_id: data})

    return sg_rules

Dictionary

{'SecurityGroups': [{'sg-aaaaaaaa': [{'FromPort': 22, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 22, 'U
serIdGroupPairs': []}, {'FromPort': 6556, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 6556, 'UserIdGroup
Pairs': []}]}, {'sg-bbbbbbbb': [{'FromPort': 61137, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 61137, 'UserIdGro
upPairs': []}, {'FromPort': 3389, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 3389, 'UserIdGroupPairs':
[]}]}]}

Test

sg_ids = get_sg(cidr, region)
sg_rules = get_rules(sg_ids, region)

print(sg_rules['SecurityGroups'][0]['sg-aaaaaaaa']) # OK
print(sg_rules['SecurityGroups'][0]['sg-bbbbbbbb']) # KeyError

Error

Traceback (most recent call last):
File "aws_sg_test.py", line 135, in <module>
    main()
File "aws_sg_test.py", line 131, in main
    update(args.cidr, args.region)
File "aws_sg_test.py", line 105, in update
    print(sg_rules['SecurityGroups'][0]['sg-bbbbbbbb']) # KeyError
KeyError: 'sg-bbbbbbbb'

Upvotes: 0

Views: 3330

Answers (1)

Salmaan P
Salmaan P

Reputation: 857

You are accessing the wrong index. This will fix it.

print(sg_rules['SecurityGroups'][1]['sg-bbbbbbbb'])

Upvotes: 5

Related Questions