Skip to content

Instantly share code, notes, and snippets.

@elyscape
Last active August 29, 2015 14:13
Show Gist options
  • Save elyscape/b724bbd8d1e41da64f89 to your computer and use it in GitHub Desktop.
Save elyscape/b724bbd8d1e41da64f89 to your computer and use it in GitHub Desktop.
Puppet::Parser::Functions::newfunction(
:fqdn_rand_base64,
:arity => -2,
:type => :rvalue,
:doc => "Usage: `fqdn_rand_base64(LENGTH, [SEED])`. LENGTH is required and
must be a positive integer; SEED is optional and may be any number or string.
Generates a random base64 string LENGTH characters long, 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.)") do |args|
raise ArgumentError, "First argument must be positive integer" unless args[0].to_i > 0
length = args.shift.to_i
ints = (length.to_f / 4.0).ceil
numeric_salt = []
# generate enough unique 4-byte integers with fqdn_rand to build our string
for current in 1..ints
numeric_salt << function_fqdn_rand([2**32, (args + [current]).join(':')]).to_i
end
# pack into base64
[numeric_salt.pack('L*')].pack('m0')[0, length]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment