2011-03-11 19:30:49 +01:00
|
|
|
#
|
2011-03-14 00:39:43 +01:00
|
|
|
# load_variables.rb
|
2011-03-03 03:37:26 +01:00
|
|
|
#
|
2011-03-03 02:48:35 +01:00
|
|
|
|
2011-03-03 03:37:26 +01:00
|
|
|
module Puppet::Parser::Functions
|
2011-03-14 00:39:43 +01:00
|
|
|
newfunction(:load_variables, :type => :statement, :doc => <<-EOS
|
|
|
|
This function will allow for loading variables from an external YAML
|
|
|
|
file and expose them for further use inside the Puppet manifest file ...
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
Given following content of the data.yaml file:
|
|
|
|
|
|
|
|
---
|
|
|
|
host1.example.com:
|
|
|
|
foo: bar
|
|
|
|
baz: quux
|
|
|
|
question: 42
|
|
|
|
host2.example.com:
|
|
|
|
abc: def
|
|
|
|
this: that
|
|
|
|
darth: vader
|
|
|
|
|
|
|
|
Then calling load_variables in Puppet manifest file as follows:
|
|
|
|
|
|
|
|
load_variables("/etc/puppet/data.yaml", $fqdn)
|
|
|
|
|
|
|
|
Will result in addition of variables $foo, $baz and $question
|
|
|
|
for matching host name as per the variable $fqdn ...
|
|
|
|
|
|
|
|
Another example which uses per-host file:
|
|
|
|
|
|
|
|
Given following content of the file data-host1.example.com.yaml:
|
|
|
|
|
|
|
|
---
|
|
|
|
foo: bar
|
|
|
|
|
|
|
|
Then when we call load_variables like this:
|
|
|
|
|
|
|
|
load_variables("/etc/puppet/data-$fqdn.yaml")
|
|
|
|
|
|
|
|
This will result in a variable $foo being added and ready for use.
|
|
|
|
EOS
|
|
|
|
) do |arguments|
|
2011-03-13 00:05:56 +01:00
|
|
|
|
2011-03-13 00:15:02 +01:00
|
|
|
raise(Puppet::ParseError, "Wrong number of arguments " +
|
|
|
|
"given (#{arguments.size} for 2)") if arguments.size < 2
|
2011-03-13 00:05:56 +01:00
|
|
|
|
2011-03-03 03:37:26 +01:00
|
|
|
data = {}
|
2011-03-03 02:48:35 +01:00
|
|
|
|
2011-03-13 00:05:56 +01:00
|
|
|
file = arguments[0]
|
|
|
|
key = arguments[1] if arguments[1]
|
2011-03-03 02:48:35 +01:00
|
|
|
|
2011-03-03 03:37:26 +01:00
|
|
|
if File.exists?(file)
|
|
|
|
|
|
|
|
begin
|
|
|
|
data = YAML.load_file(file)
|
|
|
|
rescue => error
|
2011-03-11 19:30:49 +01:00
|
|
|
raise(Puppet::ParseError, "Unable to load data " +
|
|
|
|
"from the file `%s': %s" % file, error.to_s)
|
2011-03-03 02:48:35 +01:00
|
|
|
end
|
2011-03-03 03:37:26 +01:00
|
|
|
|
2011-03-11 19:30:49 +01:00
|
|
|
raise(Puppet::ParseError, "Data in the file `%s' " +
|
|
|
|
"is not a hash" % file) unless data.is_a?(Hash)
|
2011-03-03 03:37:26 +01:00
|
|
|
|
2011-03-03 13:14:56 +01:00
|
|
|
data = ((data[key] and data[key].is_a?(Hash)) ? data[key] : {}) if key
|
2011-03-03 02:48:35 +01:00
|
|
|
end
|
|
|
|
|
2011-03-03 03:37:26 +01:00
|
|
|
data.each { |param, value| setvar(param, strinterp(value)) }
|
2011-04-23 02:18:52 +02:00
|
|
|
end
|
|
|
|
end
|
2011-03-03 03:37:26 +01:00
|
|
|
|
2011-03-03 04:08:32 +01:00
|
|
|
# vim: set ts=2 sw=2 et :
|