Skip to content

Instantly share code, notes, and snippets.

@rafaelfelix
Forked from drohr/ec2tags.rb
Last active January 17, 2020 08:55
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save rafaelfelix/5937611 to your computer and use it in GitHub Desktop.
Save rafaelfelix/5937611 to your computer and use it in GitHub Desktop.
Hack to get ec2 tags to facter. Depends on aws-cli (https://github.com/aws/aws-cli), jq (http://stedolan.github.io/jq/) and the JSON RubyGem (http://rubygems.org/gems/json)
require 'facter'
require 'json'
if Facter.value("ec2_instance_id") != nil
instance_id = Facter.value("ec2_instance_id")
region = Facter.value("ec2_placement_availability_zone")[0..-2]
tags = Facter::Util::Resolution.exec("aws ec2 describe-tags --filters \"name=resource-id,values=#{instance_id}\" --region #{region} | jq '[.Tags[] | {key: .Key, value: .Value}]'")
parsed_tags = JSON.parse(tags)
parsed_tags.each do |tag|
fact = "ec2_tag_#{tag["key"]}"
Facter.add(fact) { setcode { tag["value"] } }
end
end
@zarmstrong
Copy link

I've forked the code written by @drohr (https://gist.github.com/drohr/5048751) that you commented on to take into account non-word (\w) characters in key or value. Also doesn't require anything extra like jq or JSON rubygem.

https://gist.github.com/zarmstrong/6893172

@mlehner616
Copy link

I've forked the code that uses the same logic as this gist but removed the 'jq' requirement by using Amazon's --query parameter. The query is slightly different but the output should match exactly. For some reason the gist from @zarmstrong gave me issues with tags that had spaces and '-' characters so I opted to stay with the one provided here but needed to remove the 'jq' requirement.

https://gist.github.com/mlehner616/ae99de4966e579afe76b

@dragosboca
Copy link

I've forked your code to use only aws-sdk; no more shell exec calls.
(https://gist.github.com/dragosboca/e4d7b65f3892fd11e456)

@edsonmarquezani
Copy link

Hello, I rewrote it as an external fact (Puppet >= 3.4, Facter >= 2.0.1) in pure Bash. It goes inside 'your_module/facts.d' directory and must have exec bit set.
It still depends on 'jq' and aws-clid, plus 'sed', 'tr' (for lower-casing) and 'facter' itself. (I think those last will be always available in any standard system.)

https://gist.github.com/edsonmarquezani/d09056077c3025c04a35

@edsonmarquezani
Copy link

In case you are using an stock version of Facter, that version gets 'region' and 'instanceId' from metadata service directly, but thus, depends on 'curl'.

https://gist.github.com/edsonmarquezani/430509169fe914217367

@feniix
Copy link

feniix commented Aug 23, 2015

Since we are at it, this is my version 🎱
https://gist.github.com/feniix/eb9cb233f903f62280d6

@butlern
Copy link

butlern commented Jun 28, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment