通过带有Ruby的通配符列出EC2实例

时间:2016-05-17 18:16:48

标签: ruby amazon-ec2 aws-sdk

我想列出名称中包含 loadtest 的所有实例。

我尝试了各种形式的filterfilters失败 到目前为止我所拥有的是:

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}

1 个答案:

答案 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