我需要从 AWS 中提取所有 RUNNING PUBLIC Ip,我正在使用以下代码:
def gather_public_ip():
regions = ['us-west-2', 'eu-central-1', 'ap-southeast-1']
combined_list = [] ##This needs to be returned
for region in regions:
instance_information = [] # I assume this is a list, not dict
ip_dict = {}
client = boto3.client('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY,
region_name=region, )
instance_dict = client.describe_instances().get('Reservations')
for reservation in instance_dict:
for instance in reservation['Instances']: # This is rather not obvious
if instance[unicode('State')][unicode('Name')] == 'running' and instance[unicode('PublicIpAddress')] != None:
ipaddress = instance[unicode('PublicIpAddress')]
tagValue = instance[unicode('Tags')][0][unicode('Value')] # 'Tags' is a list, took the first element, you might wanna switch this
zone = instance[unicode('Placement')][unicode('AvailabilityZone')]
info = ipaddress, tagValue, zone
instance_information.append(info)
combined_list.append(instance_information)
return combined_list
Run Code Online (Sandbox Code Playgroud)
这对我不起作用,它给了我错误:
ipaddress = instance[unicode('PublicIpAddress')]
KeyError: u'PublicIpAddress'
Run Code Online (Sandbox Code Playgroud)
PublicIpAddress这个字典中不存在原因..有人可以帮我吗?
使用get()代替dict[key]。get()不会提高一个KeyError. 下面是一些将解释的示例。
>>> test = {'xxx':123}
>>> test['xxx']
123
>>> test['yyy']
KeyError: 'yyy'
>>> test.get('yyy')
>>> test.get('yyy') is None
True
Run Code Online (Sandbox Code Playgroud)
您可以'PublicIpAddress'按如下方式检查是否不存在。
ipaddress = instance.get(u'PublicIpAddress')
if ipaddress is None:
# Do Something
Run Code Online (Sandbox Code Playgroud)
编辑
if instance[u'State'][u'Name'] == 'running' and instance.get(u'PublicIpAddress') is not None:
print instance.get(u'PublicIpAddress')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9170 次 |
| 最近记录: |