[英]Iterating through describe_instances() to print key & value boto3
我目前正在編寫一個 python 腳本來打印有關使用 Boto3 在 AWS 上運行 EC2 實例的信息。 我正在嘗試打印 InstanceID、InstanceType 和 PublicIp。 我查看了 Boto3 的文檔和示例腳本,所以這就是我正在使用的:
import boto3
ec2client = boto3.client('ec2')
response = ec2client.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
instance_id = instance["InstanceId"]
instance_type = instance["InstanceType"]
instance_ip = instance["NetworkInterfaces"][0]["Association"]
print(instance)
print(instance_id)
print(instance_type)
print(instance_ip)
當我運行它時,“實例”會打印一大塊 json 代碼、我的實例 ID 和類型。 但是自從添加了 NetworkInterfaces 后,我收到了一個錯誤。
instance_ip = instance["NetworkInterfaces"][0]["Association"]
返回:
Traceback (most recent call last):
File "/Users/me/AWS/describeInstances.py", line 12, in <module>
instance_ip = instance["NetworkInterfaces"][0]["Association"]
KeyError: 'Association'
嘗試打印 PublicIp 時我做錯了什么?
以下是 NetworkInterfaces 的結構以供參考:
可以在此處找到供參考的完整響應語法( https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances )
Association
人並不總是可能在場。 此外,一個實例可能有多個接口。 所以你的工作循環可能是:
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
instance_id = instance["InstanceId"]
instance_type = instance["InstanceType"]
#print(instance)
print(instance_id, instance_type)
for network_interface in instance["NetworkInterfaces"]:
instance_ip = network_interface.get("Association", "no-association")
print(' -', instance_ip)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.