Reputation: 3506
I want to list all instances that have a name containing loadtest.
I've tried various forms of filter
and filters
unsuccessfully
What I have so far is:
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
I wish to get a hash similar to :
{Name: loadtest-1west, id: <someid>, state: running}
{Name: loadtest-10west, id: <someid>, state: stopped}
Upvotes: 1
Views: 572
Reputation: 2761
Assuming you're using the Name
tag on your instances, the describe_instances
call would look like this:
ec2.describe_instances({
filters: [{ name: 'tag:Name', values: ['loadtest*'] }]
})
For tags, the filter name is tag:<name-of-tag>
.
You can just iterate through the response and output the fields you want (example without pagination):
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
Upvotes: 4