Is there a way to pass filters to the instances API call? I'd like to filter the response by tags. I checked the documentation but didn't see a way to do that. I know the JS API supports it etc..
Yes, there are multiple ways to filter EC2 instances. If you are using AWS::EC2::Client, you can pass filter options directly to the #describe_instances call:
ec2 = AWS::EC2::Client.new
ec2.describe_instances(filters: [{name:'filter-name', values:['filter-value']}])
If you are using the resource interface, you can use the #filter method:
ec2 = AWS::EC2.new
ec2.instances.filter('filter-name', ['filter-value']).each { |instance| ... }
To filter by tags, you use the filter name of "tag:TAGNAME". This works in both the client and resource interface.
# filter instances that have the tag name "role" and value "web"
ec2.instances.filter("tag:role", "web").each { |instance| ... }
You can get a full list of supported filters from the EC2 API reference documentation: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html
Can you provide an example where multiple filters are applied? I'm attempting to do this, but I'm failing horribly. Sorry for digging up a post from 2014 :(
Since it took me a while too, and I ran across this with my search terms, here's a multi-filter example that should find instances that have tag Active (any value), has Stage set to production, and is in state running.
This uses the v2 SDK.
f = [
{ name: 'tag-key', values: ['Active'] },
{ name: 'tag:Stage', values: ['production'] },
{ name: 'instance-state-name', values: ['running'] }
]
ec2_client.describe_instances(filters: f)
Hope that helps.
@kylev Awesome. Thank you so much for the example. I really appreciate it.
How can I filter and sort by launch-time?
Most helpful comment
Since it took me a while too, and I ran across this with my search terms, here's a multi-filter example that should find instances that have tag
Active(any value), hasStageset toproduction, and is in state running.This uses the v2 SDK.
Hope that helps.