在尝试访问字典中的键时始终获取KeyError

时间:2017-07-05 18:14:45

标签: python dictionary aws-sdk boto3

我正在使用AWS的Boto3编写Python脚本来管理安全组。我创建了一个字典来获取组ID及其属性。我可以访问sg-aaaaaaaa的属性,但当我尝试访问sg-bbbbbbbb时,它始终会抛出KeyError

我如何创建词典

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

词典

{'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':
[]}]}]}

测试

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

错误

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'

1 个答案:

答案 0 :(得分:5)

您正在访问错误的索引。这将解决它。

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