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