Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filtering EC2 Instances #635

Closed
jtruelove opened this issue Sep 27, 2014 · 5 comments
Closed

Filtering EC2 Instances #635

jtruelove opened this issue Sep 27, 2014 · 5 comments

Comments

@jtruelove
Copy link

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..

@trevorrowe
Copy link
Member

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

@bmurtagh
Copy link

bmurtagh commented Dec 3, 2015

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 :(

@kylev
Copy link

kylev commented Jan 7, 2016

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.

@bmurtagh
Copy link

bmurtagh commented Jan 7, 2016

@kylev Awesome. Thank you so much for the example. I really appreciate it.

@pruan-rht
Copy link

How can I filter and sort by launch-time?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants