Reputation: 863
Is there anyway I can ensure that the pool of numbers used when calling fqdn_rand will never pick the same number in a single puppet run?
I have a cronjob and I never want any of my 5 jobs to run on the same day. I've been using fqdn_rand to generate the jobs on random days but finding some servers will have jobs which run on the same days. In my mind if these numbers are removed from the possible selected numbers, I'll never get the same result.
Upvotes: 0
Views: 398
Reputation: 180998
Is there anyway I can ensure that the pool of numbers used when calling fqdn_rand will never pick the same number in a single puppet run?
You cannot ensure that multiple calls to fqdn_rand()
will all return distinct values. However, you can use fqdn_rand()
to perform a selection of multiple items without duplication. There are several ways you could do that, but I'm going to suggest combining it with the reduce()
function to perform a (partial) shuffle of the list of options from which you want to select.
It isn't clear in the question whether you want to select from days of the week, days of the month, or something else, but for simplicity, I'll assume that you are selecting among days of the week, in the form of numbers 1 through 7:
$day_numbers = [ 1, 2, 3, 4, 5, 6, 7 ]
Although Puppet does not have general purpose looping statements such as for
or while
, you can iterate (among other ways) by using one of several iteration functions to process an iterable value. For example:
$selected = [ 0, 1, 2, 3, 4 ].reduce($day_numbers) |$numbers, $i| {
$selection = fqdn_rand($day_numbers.length - $i - 1, $i)
[
$numbers[0, $i], # The already selected numbers
$numbers[$selection + $i, -1], # The tail starting at the next selection
$numbers[$i, $selection] # The slice between the previous two
].flatten
}[0, 5]
That executes the lambda five times, associating successive values from 0 to 4 with variable $i
. On the initial iteration, $day_numbers
is associated with $numbers
. On each subsequent iteration, the return value of the lambda's previous iteration is associated with $numbers
.
On each iteration of the lambda, the $i
elements selected in previous iterations occupy the first $i
positions of $numbers
. The fqdn_rand()
function is used to compute the index of one of the other elements, then the tail is rotated to bring the selected element into position.
Ultimately, an array containing the first five elements of the result (those being all the selected values) is assigned to $selected
.
Upvotes: 2