我想列出名称中包含 loadtest 的所有实例。
我尝试了各种形式的filter
和filters
失败
到目前为止我所拥有的是:
ec2 = Aws::EC2::Client.new
ec2.describe_instances.each do |page|
page.reservations.each do |reservation|
reservation.instances.each do |instance|
puts instance.tags
puts instance.state
puts instance.state.name
end
end
end
我希望得到类似的哈希:
{Name: loadtest-1west, id: <someid>, state: running}
{Name: loadtest-10west, id: <someid>, state: stopped}
答案 0 :(得分:3)
假设您在实例上使用Name
标记,describe_instances
调用将如下所示:
ec2.describe_instances({
filters: [{ name: 'tag:Name', values: ['loadtest*'] }]
})
对于代码,过滤器名称为tag:<name-of-tag>
。
您可以遍历响应并输出所需的字段(不带分页的示例):
def name_tag(tags)
name = tags.select {|t| t.key == 'Name'}
name[0].value if name.length > 0
end
ec2.describe_instances({
filters: [{ name: 'tag:Name', values: ['loadtest*'] }]
}).reservations.each do |reservation|
reservation['instances'].each do |instance|
name = name_tag(instance.tags)
puts "{Name: #{name}, id: #{instance.instance_id}, state: #{instance.state.name}}"
end
end