請幫我解決這個問題:當我試圖運行下面的腳本,它總是返回該錯誤:KeyError異常: 'AvailabilityZone'KeyError異常: 'AvailabilityZone'
client.describe_instances(過濾器= [ {'Name':'instance-state-name','Values':['running',]},],)
另外,我觀察到響應中沒有AvailabilityZone字符串。
示例代碼片段:所有的
import boto3
import collections
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
running_instances = {}
for instance in instances:
az = instance.placement['AvailabilityZone']
os = instance.platform
instance_type = instance.instance_type
if os is None:
os = 'Linux/UNIX'
else:
os = 'Windows'
if az not in running_instances:
running_instances[az] = {}
if os not in running_instances[az]:
running_instances[az][os] = {}
if instance_type not in running_instances[az][os]:
running_instances[az][os][instance_type] = 0
running_instances[az][os][instance_type] += 1
client = boto3.client('ec2')
response = client.describe_reserved_instances(
Filters=[
{
'Name': 'state',
'Values': [
'active',
]
}
],
)
cnt = collections.Counter()
reserved_instances = {}
for instance in response['ReservedInstances']:
az = instance['AvailabilityZone']
os = instance['ProductDescription']
instance_type = instance['InstanceType']
instance_count = instance['InstanceCount']
if az not in reserved_instances:
reserved_instances[az] = {}
if os not in reserved_instances[az]:
reserved_instances[az][os] = {}
if instance_type not in reserved_instances[az][os]:
reserved_instances[az][os][instance_type] = 0
reserved_instances[az][os][instance_type] += instance_count
print("****** Running Instances breakdown *****")
print(running_instances)
print("****** Reserved Instance breakdown *****")
print(reserved_instances)
您好,感謝您的幫助... 我想你的建議, 我得到一個錯誤這樣的: 預約在result [「預訂」]: 未定義的變量:導致 當我把它改成: 預約回覆['Reservations']: 我得到: KeyError:'Reservations' –
@IrfanJunaid您是否注意到我改變了您的代碼並將值賦給'result',即'result = ec2.instances。過濾器....'而不是你的代碼'實例= ec2.instance s.filter ...'。順便說一下,您的describe_reserved_instances語法是正確的。 – mootmoot
我還是不明白。試過你的編輯,但仍然是相同的錯誤。這是簡化代碼:[code](https://codeshare.io/2Werq3) –