X-Git-Url: https://git.adam-barratt.org.uk/?a=blobdiff_plain;ds=sidebyside;f=3rdparty%2Fmodules%2Fstdlib%2Flib%2Fpuppet%2Ffunctions%2Fseeded_rand_string.rb;fp=3rdparty%2Fmodules%2Fstdlib%2Flib%2Fpuppet%2Ffunctions%2Fseeded_rand_string.rb;h=f3d1dcc4fa51945e4e2040531c155d5e550c85e7;hb=9dd86576df2182653f8e96f51f11c917341eb4ce;hp=0000000000000000000000000000000000000000;hpb=88887aa2a8ca345d6f79fccb336a9bb9ae8443a2;p=mirror%2Fdsa-puppet.git diff --git a/3rdparty/modules/stdlib/lib/puppet/functions/seeded_rand_string.rb b/3rdparty/modules/stdlib/lib/puppet/functions/seeded_rand_string.rb new file mode 100644 index 000000000..f3d1dcc4f --- /dev/null +++ b/3rdparty/modules/stdlib/lib/puppet/functions/seeded_rand_string.rb @@ -0,0 +1,29 @@ +# Generates a consistent random string of specific length based on provided seed. +# +# @example Generate a consistently random string of length 8 with a seed: +# seeded_rand_string(8, "${module_name}::redis_password") +# +# @example Generate a random string from a specific set of characters: +# seeded_rand_string(5, '', 'abcdef') +Puppet::Functions.create_function(:seeded_rand_string) do + # @param length Length of string to be generated. + # @param seed Seed string. + # @param charset String that contains characters to use for the random string. + # + # @return [String] Random string. + dispatch :rand_string do + param 'Integer[1]', :length + param 'String', :seed + optional_param 'String[2]', :charset + end + + def rand_string(length, seed, charset = nil) + require 'digest/sha2' + + charset ||= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' + + random_generator = Random.new(Digest::SHA256.hexdigest(seed).to_i(16)) + + Array.new(length) { charset[random_generator.rand(charset.size)] }.join + end +end