I’m using Boto3 of AWS to describe the security group and trying to access the FromPort
key for all the security groups available in a particular region. But when I’m trying to do so it will list some of the ports and then throws the KeyError
.
Code:
JavaScript
x
9
1
import boto3
2
3
client = boto3.client('ec2')
4
response = client.describe_security_groups()
5
6
for sg in response['SecurityGroups']:
7
for ip in sg['IpPermissions']:
8
print(ip['FromPort'])
9
Output:
JavaScript
1
19
19
1
80
2
5432
3
22
4
22
5
3622
6
8443
7
3
8
80
9
3622
10
8080
11
5432
12
22
13
8443
14
443
15
Traceback (most recent call last):
16
File ".a.py", line 8, in <module>
17
print(ip['FromPort'])
18
KeyError: 'FromPort'
19
Advertisement
Answer
Your code is assuming that the entry you are trying to print is always in the response you get back. You can make the code more robust like this:
Replace
JavaScript
1
2
1
ip['FromPort']
2
with
JavaScript
1
2
1
ip.get('FromPort','((missing))')
2