summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorHunter Haugen <hunter@puppetlabs.com>2015-04-09 10:45:38 -0700
committerHunter Haugen <hunter@puppetlabs.com>2015-04-09 10:45:38 -0700
commit8fba5c058ba344421796cceca8f96dffcba0a4fc (patch)
tree8e452e9979d633a228352702c5f3e3873f286e7f /lib
parent487e8d4cd7384e9c3170f93a71f14c0a78766a3f (diff)
parenta82266c256784c4af229e026b00a4dcf9e779270 (diff)
Merge pull request #405 from elyscape/feature/fqdn_rand_strings
(MODULES-1715) Add FQDN-based random string generator
Diffstat (limited to 'lib')
-rw-r--r--lib/puppet/parser/functions/fqdn_rand_string.rb34
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/puppet/parser/functions/fqdn_rand_string.rb b/lib/puppet/parser/functions/fqdn_rand_string.rb
new file mode 100644
index 0000000..785c9fd
--- /dev/null
+++ b/lib/puppet/parser/functions/fqdn_rand_string.rb
@@ -0,0 +1,34 @@
+Puppet::Parser::Functions::newfunction(
+ :fqdn_rand_string,
+ :arity => -2,
+ :type => :rvalue,
+ :doc => "Usage: `fqdn_rand_string(LENGTH, [CHARSET], [SEED])`. LENGTH is
+ required and must be a positive integer. CHARSET is optional and may be
+ `undef` or a string. SEED is optional and may be any number or string.
+
+ Generates a random string LENGTH characters long using the character set
+ provided by CHARSET, combining the `$fqdn` fact and the value of SEED for
+ repeatable randomness. (That is, each node will get a different random
+ string from this function, but a given node's result will be the same every
+ time unless its hostname changes.) Adding a SEED can be useful if you need
+ more than one unrelated string. CHARSET will default to alphanumeric if
+ `undef` or an empty string.") do |args|
+ raise(ArgumentError, "fqdn_rand_string(): wrong number of arguments (0 for 1)") if args.size == 0
+ Puppet::Parser::Functions.function('is_integer')
+ raise(ArgumentError, "fqdn_rand_base64(): first argument must be a positive integer") unless function_is_integer([args[0]]) and args[0].to_i > 0
+ raise(ArgumentError, "fqdn_rand_base64(): second argument must be undef or a string") unless args[1].nil? or args[1].is_a? String
+
+ Puppet::Parser::Functions.function('fqdn_rand')
+
+ length = args.shift.to_i
+ charset = args.shift.to_s.chars.to_a
+
+ charset = (0..9).map { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a if charset.empty?
+
+ rand_string = ''
+ for current in 1..length
+ rand_string << charset[function_fqdn_rand([charset.size, (args + [current.to_s]).join(':')]).to_i]
+ end
+
+ rand_string
+end