Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get ec2 instances with a certain tag using aws sdk

I am trying to figure out what is the best way to get a list of ec2 instances with a certain tag for example "testing" using the ruby aws sdk.

ec2 = AWS::EC2.new(:access_key_id => "XXXXXXXXXXXXX", :secret_access_key => "YYYYYYYYY")
ec2list = ec2.instances.filter("Name", "testing)

This does not seem to work for some reason. It was thinking it will filter out the collection and just give me instances with tag testing. Is there a way to do this using the ruby sdk? thank you.

like image 621
user1781472 Avatar asked Apr 15 '14 22:04

user1781472


People also ask

How do I find my EC2 instance tags?

To get started, you can enable tags on instance metadata at launch in the console or CLI and you can save this launch setting in a launch template. You can also use the CLI to enable tags on instance metadata on a running instance or on a stopped instance.

How do I search AWS tags?

To find resources to tagSign in to the AWS Management Console , choose Resource Groups, and then choose Tag Editor. (optional) Choose regions in which to search for resources to tag. By default, your current region is selected.

Which AWS CLI command correctly adds tags to an EC2 instance?

If you're using the Amazon EC2 API, the AWS CLI, or an AWS SDK, you can use the CreateTags EC2 API action to apply tags to existing resources. Additionally, some resource-creating actions enable you to specify tags for a resource when the resource is created.

Does AWS CloudFormation support EC2 tags?

Q: Does AWS CloudFormation support Amazon EC2 tagging? Yes. Amazon EC2 resources that support the tagging feature can also be tagged in an AWS template.


2 Answers

If you want the tag "Name" with the value of "testing" use:

instances = resource.instances(
  filters: [
    { 
      name: 'tag:Name',
      values: ["testing"] 
    }
  ]
)

For all instances with a tag key of "testing" the following is used.

instances = resource.instances(
  filters: [
    { 
      name: 'tag:Key',
      values: ["testing"] 
    }
  ]
)

See the #instances docs for more filter options.

like image 136
Christopher Bradford Avatar answered Sep 20 '22 21:09

Christopher Bradford


This worked for me:

ec2.instances.tagged("testing")
like image 37
calvin Avatar answered Sep 20 '22 21:09

calvin