Created
August 15, 2012 18:55
-
-
Save skottler/3362547 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'puppet' | |
require 'net/http' | |
require 'yaml' | |
Factsdir = "/var/lib/puppet/yaml/facts" | |
Foreman = "http://foreman" | |
node = ARGV[0] | |
def die(msg) | |
$stderr.puts(msg) | |
Process.exit 1 | |
end | |
def get_puppet_env(fqdn) | |
factsfile = File.join(Factsdir, "#{fqdn}.yaml") | |
y = YAML.load_file(factsfile) | |
p = Puppet::Node::Facts.new(y.name, y.values) | |
p.values['environment'] | |
end | |
def stat_file | |
FileUtils.mkdir_p "#{puppetdir}/yaml/foreman/" | |
"#{puppetdir}/yaml/foreman/#{certname}.yaml" | |
end | |
def upload_facts | |
# Temp file keeping the last run time | |
last_run = File.exists?(stat_file) ? File.stat(stat_file).mtime.utc : Time.now - 365*24*60*60 | |
filename = "#{puppetdir}/yaml/facts/#{certname}.yaml" | |
last_fact = File.stat(filename).mtime.utc | |
if last_fact > last_run | |
fact = File.read(filename) | |
begin | |
uri = URI.parse("#{url}/fact_values/create?format=yml") | |
req = Net::HTTP::Post.new(uri.path) | |
req.set_form_data('facts' => fact) | |
res = Net::HTTP.new(uri.host, uri.port) | |
res.use_ssl = uri.scheme == 'https' | |
res.verify_mode = OpenSSL::SSL::VERIFY_NONE if res.use_ssl | |
res.start { |http| http.request(req) } | |
rescue => e | |
raise "Could not send facts to Foreman: #{e}" | |
end | |
end | |
end | |
def cache result | |
File.open(stat_file, 'w') {|f| f.write(result) } | |
end | |
def read_cache | |
File.read(stat_file) | |
rescue => e | |
raise "Unable to read from Cache file: #{e}" | |
end | |
def get_foreman_yaml(fqdn) | |
foreman_url = "#{Foreman}/node/#{fqdn}?format=yml" | |
url = URI.parse(foreman_url) | |
req = Net::HTTP::Get.new(foreman_url) | |
res = Net::HTTP.start(url.host, url.port) { |http| | |
http.request(req) | |
} | |
if res.class != Net::HTTPOK | |
die "Error retrieving fqdn %s: %s" % [fqdn, res.class] | |
else | |
res.body | |
end | |
end | |
upload_facts | |
def get_foreman_env(yamlfile) | |
YAML.load(yamlfile)['environment'] | |
end | |
foreman_yaml = get_foreman_yaml(node) | |
foreman_env = get_foreman_env(foreman_yaml) | |
puppet_env = get_puppet_env(node) | |
if puppet_env == foreman_env | |
puts foreman_yaml | |
else | |
y = {} | |
y['parameters'] = {} | |
y['parameters']['real_env'] = foreman_env | |
y['environment'] = foreman_env | |
y['classes'] = ['puppet::config::environment'] | |
puts y.to_yaml | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment