Alex Brickman Alex Brickman - 3 months ago 48
Ruby Question

how to access aws ec2 tags

I am trying to figure out the way to access AWS tag and then run some code on the instance with the tag.

How can I access the each key and value of the instance tags using AWS SDK for Ruby - Version 2?

#!/usr/bin/ruby
require 'rubygems'
require 'aws-sdk'
require 'yaml'
Aws.config.update({
region: region,
credentials: Aws::Credentials.new(ENV_YML['access_key_id'], ENV_YML['secret_access_key'])
})

ec2 = Aws::EC2::Resource.new
ec2.instances.each do |instance|
tags = instance.tags
tags.each do |num|
### pseudo code
puts tag owner # i want to get the value of tag owner
if tag owner = "test" #then run on this tag if
puts tag name #print the value of tag name
#some code
else
#some code
end
end


when I do something like this :

ec2.instances.each do |instance|
tags = instance.tags
tags.each do |num|
puts num
end
end


The output is:

#<struct Aws::EC2::Types::Tag key="Name", value="test.ec2.blabla.int">


But I want to be able to get only the value by calling the key(name) or whatever.

Please help,

Thanks.

Answer

you can use facter gem :

ec2.instances.each do |instance|
  tag_name = Facter::Util::Resolution.exec("ec2-describe-tags --region eu-west-1 --filter \"resource-id=#{instance.id}\" --filter key=Name | cut -f 5")
Comments