Skip to content

Instantly share code, notes, and snippets.

@ozbillwang
Forked from igorlg/aws_tags.rb
Last active April 14, 2023 13:42
Show Gist options
  • Save ozbillwang/17f0c20a4d7b0cea0357 to your computer and use it in GitHub Desktop.
Save ozbillwang/17f0c20a4d7b0cea0357 to your computer and use it in GitHub Desktop.
Facter for AWS EC2 Instance Tags

Installation

Check out the [Facter documentation|https://docs.puppetlabs.com/facter/2.3/custom_facts.html#loading-custom-facts]

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_, 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

# aws-sdk version 2
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
# This custom fact is used to query the AWS EC2 API to determine
# the tags that has been associated with the ec2 node.
# Gem dependencies:
# aws-sdk version 1
require 'facter'
require 'yaml'
require 'open-uri'
begin
require 'aws-sdk'
rescue LoadError
Facter.debug "No aws-sdk to gather facts"
end
def metadata(id = "")
open("http://169.254.169.254/latest/meta-data/#{id||=''}").read.split("\n")[0]
rescue => details
Facter.warn "Could not retrieve ec2 metadata: #{details.message}"
end
def region
# Get rid of the last character of availability zone to find the region
region = metadata('placement/availability-zone')[0..-2]
Facter.debug "Determined region to be #{region}"
region
end
begin
ec2 = AWS::EC2.new
ec2 = ec2.regions[region]
exclusion_list=['Name']
instance = ec2.instances[metadata('instance-id')]
instance.tags.each do |key, value|
if not exclusion_list.include? key
Facter.add(key) { setcode { value } }
end
end
rescue => details
Facter.warn("Unable to get ec2 tags: #{details.message}")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment