aws / aws-sdk-ruby

The official AWS SDK for Ruby.
https://aws.amazon.com/sdk-for-ruby/
Apache License 2.0
3.58k stars 1.23k forks source link

[Question] How do I filter a list of EC2 instances by tag(s)? #732

Closed dandunckelman closed 9 years ago

dandunckelman commented 9 years ago

This may be a silly question, but I can't seem to figure out how to do this from the instructions in the documentation.

Here's what I'm trying:

instances = Aws::EC2::Resource.new.instances({
    :filters => [
        { :tag => "Name=tag:app_type,Values=spark" }
    ]
})

With variations like this:

instances = Aws::EC2::Resource.new.instances({
    :filters => [
        { :tag => { app_type: "spark" }
    ]
})

instances = Aws::EC2::Resource.new.instances({
    :filters => [
        {
            :tag => {
                :key => "app_type",
                :value => "spark"
            }
        }
    ]
})

Everytime I try to iterate on the collection of instances, I get errors like this:

instances.each { |i| puts i }
ArgumentError: unexpected value at params[:filters][0][:tag]

Thanks for the help.

trevorrowe commented 9 years ago

To apply filters, you pass an array of hashes. Valid hash keys are :name, and :key. The filter :name is one of the filters documented here (click the request parameters tag for the valid filter list): http://docs.aws.amazon.com/sdkforruby/api/Aws/EC2/Client.html#describe_instances-instance_method

To filter by a tag name and value pair, its a bit tricky, because the filter name is the string "tag:#{tag_name}". For example:

ec2 = Aws::EC2::Resource.new
instances = ec2.instances(filters: [{ name: 'tag:app_type', values:['spark'])

Hope this helps!