Python 通过ec2迭代描述实例boto3
我正在尝试获取描述实例调用的特定值。例如,如果我想从输出中获取“Hypervisor”值或Ebs具有“DeleteOnTermination”值。下面是我当前用来调用和迭代字典输出的代码Python 通过ec2迭代描述实例boto3,python,amazon-ec2,boto3,Python,Amazon Ec2,Boto3,我正在尝试获取描述实例调用的特定值。例如,如果我想从输出中获取“Hypervisor”值或Ebs具有“DeleteOnTermination”值。下面是我当前用来调用和迭代字典输出的代码 import boto3 import pprint from datetime import datetime import json client = boto3.client('ec2') filters = [{ 'Name': 'tag:Name', 'Values': ['*'] }]
import boto3
import pprint
from datetime import datetime
import json
client = boto3.client('ec2')
filters = [{
'Name': 'tag:Name',
'Values': ['*']
}]
class DatetimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
output = json.dumps((client.describe_instances(Filters=filters)), cls=DatetimeEncoder)
pprint.pprint(output)
for v in output:
print v['Hypervisor']
获取此错误:
TypeError: string indices must be integers, not str
使用pprint查看输出中的所有可用值。以下是如何通过以下方式显示信息: 下面是一些Python:
import boto3
client = boto3.client('ec2')
response = client.describe_instances()
for r in response['Reservations']:
for i in r['Instances']:
print i['InstanceId'], i['Hypervisor']
for b in i['BlockDeviceMappings']:
print b['Ebs']['DeleteOnTermination']
以下是John的答案,但已针对Python3进行了更新
import boto3
client = boto3.client('ec2')
response = client.describe_instances()
for r in response['Reservations']:
for i in r['Instances']:
print(i['InstanceId'], i['Hypervisor'])
for b in i['BlockDeviceMappings']:
print(b['Ebs']['DeleteOnTermination'])
我知道我参加聚会有点晚了,但我的可读性2美分是使用生成器理解(python 3):
导入boto3
client=boto3.client('ec2')
response=client.description_实例()
块映射=(块映射
对于答复中的保留[“保留”]
例如,在保留[“实例”]
对于实例[“BlockDeviceMappings”]中的块映射
对于块映射中的块映射:
打印(块映射[“Ebs”][“DeleteOnTermination”])
您还可以使用awscli--query
标志后面的相同查询引擎jmespath
,自动获取嵌套结果:
导入jmespath
进口boto3
client=boto3.client('ec2')
response=client.description_实例()
打印(jmespath.search)(
“保留[]。实例[]。设备块映射[]。Ebs.DeleteOnTermination”,
响应
))
或者,如果您需要更多电源,请使用pyjq
。它的语法与awscli中使用的jmespath稍有不同,但它比它有更多的优势。假设您不仅希望DeviceBlockMappings
,还希望保留与之相关的InstanceId
。在jmespath
中,您可以t真正做到这一点,因为没有对外部结构的访问,只有一个嵌套路径。在
pyjq`中,您可以执行以下操作:
导入pyjq
进口boto3
client=boto3.client('ec2')
response=client.description_实例()
打印(pyjq.all)(
{id:.保留[]。实例[]。实例id,d:.保留[]。实例[]。设备块映射[]},
响应
))
这将产生一个设备块映射列表及其相应的InstanceId,有点像mongo的展开操作:
{'id':字符串,d:{'Ebs':{'deleteonterminion':boolean}}[]
print(jmespath.search(“Reservations[].Instances[].[InstanceId,SubnetId,ImageId,PrivateIpAddress,Tags[*]]”,response))这实在太少了,不可能是一个有用的答案。请解释一下你的建议
import boto3
client = boto3.client('ec2')
response = client.describe_instances()
for r in response['Reservations']:
for i in r['Instances']:
print(i['InstanceId'], i['Hypervisor'])
for b in i['BlockDeviceMappings']:
print(b['Ebs']['DeleteOnTermination'])