Skip to content

Instantly share code, notes, and snippets.

@trevor-vaughan
Last active May 24, 2016 20:40
Show Gist options
  • Save trevor-vaughan/2c404efd0f1f881bbf56eef7bc949eb0 to your computer and use it in GitHub Desktop.
Save trevor-vaughan/2c404efd0f1f881bbf56eef7bc949eb0 to your computer and use it in GitHub Desktop.
Set your Puppet Environment from Hiera
#!/usr/bin/env ruby
require 'yaml'
# The location of the environment data file
# The format of this file should be as follows:
# <regex/hostname> : <environment>
#
# <regex/hostname>: May be either a regular expression or a simple string that
# matches against the FQDN of the system.
#
# NOTE: You *must* have '/' before and after your entry if it is a regex.
#
# <environment>: A string representation of the environemnt. This is what will
# be passed back to the Puppet Server
#
# NOTE: Entries are processed from the top down and the first match wins!
#
# EXAMPLE
#
# ---
# '/^foo\.bar/' : 'foobar' => Matches all hosts that start with foo.bar and
# places them in the 'foobar' environment.
#
# 'foo1.bar' : 'production' => Matches only 'foo1.bar' and places it in the
# 'production' environment.
# USAGE
#
# 1. Add this script to a reasonable path that the Puppet server can access.
# 2. Add, or change, the line 'node_terminus' to 'exec' in the [master] section of puppet.conf.
# 3. Set the 'external_nodes' entry in the [master] section of puppet.conf to point to this script.
# 4. Add the file '/etc/puppetlabs/puppet/environments.yaml' to your system
# 5. Restart the Puppet Server process
#
Puppet.initialize_settings
data_file = '/etc/puppetlabs/puppet/environments.yaml'
fqdn = ARGV[0]
raise("You must pass the FQDN of the host as the first argument") unless fqdn
# Set the default environment to production if there is no match
result = { 'environment' => 'production' }
if File.readable?(data_file)
environment_data = YAML.load(File.read(data_file)).to_hash
environment_data.each_pair do |host,value|
if host[0].chr == '/'
if host[-1].chr == '/'
clean_host = host[1..-2]
if Regexp.new(clean_host).match(fqdn)
result['environment'] = value.to_s.strip
break
end
else
fail("Entry '#{host}' is not a valid hostname or regex")
end
else
if host == fqdn
result['environment'] = value.to_s.strip
break
end
end
end
end
puts result.to_yaml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment