2 # Generates a consistent random string of specific length based on provided seed.
4 # @example Generate a consistently random string of length 8 with a seed:
5 # seeded_rand_string(8, "${module_name}::redis_password")
7 # @example Generate a random string from a specific set of characters:
8 # seeded_rand_string(5, '', 'abcdef')
9 Puppet::Functions.create_function(:seeded_rand_string) do
10 # @param length Length of string to be generated.
11 # @param seed Seed string.
12 # @param charset String that contains characters to use for the random string.
14 # @return [String] Random string.
15 dispatch :rand_string do
16 param 'Integer[1]', :length
18 optional_param 'String[2]', :charset
21 def rand_string(length, seed, charset = nil)
24 charset ||= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
26 random_generator = Random.new(Digest::SHA256.hexdigest(seed).to_i(16))
28 Array.new(length) { charset[random_generator.rand(charset.size)] }.join