File: seeded_rand_string.rb

package info (click to toggle)
puppet-module-puppetlabs-stdlib 9.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,448 kB
  • sloc: ruby: 3,522; sh: 46; makefile: 2
file content (32 lines) | stat: -rw-r--r-- 1,112 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# frozen_string_literal: true

# @summary
#   Generates a consistent random string of specific length based on provided seed.
#
# @example Generate a consistently random string of length 8 with a seed:
#   stdlib::seeded_rand_string(8, "${module_name}::redis_password")
#
# @example Generate a random string from a specific set of characters:
#   stdlib::seeded_rand_string(5, '', 'abcdef')
Puppet::Functions.create_function(:'stdlib::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