Skip to content

Instantly share code, notes, and snippets.

@igorlg
Last active June 6, 2016 08:16
Show Gist options
  • Save igorlg/decbd81afe33ba914972 to your computer and use it in GitHub Desktop.
Save igorlg/decbd81afe33ba914972 to your computer and use it in GitHub Desktop.
Facter for AWS EC2 Instance Tags
require 'open-uri'
require 'aws-sdk-core'
def aws_metadata(path)
return open("http://169.254.169.254/latest/meta-data/#{path}").read.split("\n")[0]
end
Aws.config[:region] = aws_metadata('placement/availability-zone')[0..-2]
Aws.config[:credentials] = Aws::InstanceProfileCredentials.new
ec2 = Aws::EC2::Client.new
filters = [
{name: "resource-type", values: ['instance']},
{name: "resource-id", values: [aws_metadata('instance-id')]},
]
tags = {}
ec2.describe_tags(:filters => filters).each do |resp|
resp[:tags].each do |tag|
tags[tag.key] = tag.value
Facter.add("aws_tag_#{tag.key}") do
setcode do
tag.value
end
end
end
end
Facter.add(:aws_tags) do
setcode do
tags.to_json
end
end
@igorlg
Copy link
Author

igorlg commented Dec 31, 2014

Installation

Check out the Facter documentation

Requirements

  • gem 'aws-sdk-core'
  • Instance must have an IAM Role with read-only permission for EC2 resources (at least ec2:Describe*). See here and here

Usage:

The value of each tag can be accessed using fact aws_tag_<tag_name>, or all tags in JSON format using fact aws_tags. Ex:

Single tag

$ facter aws_tag_name
my_ec2_instance
$ facter aws_tag_environment
Test

All Tags

$ facter aws_tags
[{"Name": "my_ec2_instance", "Environment": "Test"}]

All edits, comments and suggestions are welcome!!

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