通过ec2描述实例boto3迭代

时间:2016-06-30 01:56:15

标签: python amazon-ec2

我刚刚开始使用boto3并尝试获取描述实例调用的特定值。因此,例如,如果我想获得'Hypervisor'值或Ebs从输出中获得'DeleteOnTermintation'值。下面是我当前用于进行调用并通过字典输出进行迭代的当前代码。

<% @tree = Tree.find(@bucket.tree_id) %>
<%= render "shared/bucket_as_table", object: @tree, as: 't' %>

出现此错误:

TypeError:字符串索引必须是整数,而不是str

使用pprint查看输出中的所有可用值。

谢谢..

4 个答案:

答案 0 :(得分:13)

以下是通过AWS Command-Line Interface (CLI)

显示信息的方法
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Hypervisor, NetworkInterfaces[0].Attachment.DeleteOnTermination]'

这是一些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']

答案 1 :(得分:3)

这是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 :(得分:2)

我知道我参加聚会有点晚了,但我的2美分的可读性是使用生成器理解(python 3):

import boto3

client = boto3.client('ec2')

response = client.describe_instances()
block_mappings = (block_mapping
                  for reservation in response["Reservations"]
                  for instance in reservation["Instances"]
                  for block_mapping in instance["BlockDeviceMappings"])

for block_mapping in block_mappings:
  print(block_mapping["Ebs"]["DeleteOnTermination"])

您还可以使用jmespath(awscli --query标志后面的相同查询引擎)自动获取嵌套结果:

import jmespath
import boto3

client = boto3.client('ec2')

response = client.describe_instances()
print(jmespath.search(
    "Reservations[].Instances[].DeviceBlockMappings[].Ebs.DeleteOnTermination", 
    response
))

或者,如果需要更多电源,请使用pyjq。它的语法与awscli中使用的jmespath稍有不同,但是它具有更多的优势。假设您不仅想要DeviceBlockMappings,而且想要保留与之相关的InstanceId。在jmespath中可以t really do this, because there is no access to outer structures, just a single nestes path. In pyjq`可以执行以下操作:

import pyjq
import boto3

client = boto3.client('ec2')

response = client.describe_instances()
print(pyjq.all(
  "{id: .Reservations[].Instances[].InstanceId, d:.Reservations[].Instances[].DeviceBlockMappings[]}",
  response
))

这将产生带有相应InstanceId的设备块映射列表,有点像mongo的展开操作:

{'id': string, d: {'Ebs': {'DeleteOnTermination': boolean}}}[]

答案 3 :(得分:-2)

print(jmespath.search(“ Reservations []。Instances []。[InstanceId,SubnetId,ImageId,PrivateIpAddress,Tags [*]]”,响应))