我目前正在撰寫一個 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)
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/345160.html
