2

I have a list of IPs, I would like to use in one of chef recipe, can someone please suggest how I can generate a random list for a given node. for example, if given list is [1,2,3,4]

node 1 should get the order [3,2,1,4] node 2 should get some other random order [4,2,1,3] etc.

Thanks, Raju

Raju
  • 31
  • 5
  • Possible duplicate of [Shuffle a list and return a copy](https://stackoverflow.com/questions/30253198/shuffle-a-list-and-return-a-copy) – Sagar Gupta Aug 19 '19 at 14:23
  • 1
    Bear in mind that if you put this in a cookbook and the node is checking into a Chef server every so often, it will reshuffle the list every time the node checks in, unless you explicitly use a guard around resource that will end up using these values. That may or may not matter for use-case, but just tossing it out there. – Spencer D Aug 25 '19 at 19:56

2 Answers2

2

Code:

from random import shuffle


def get_shuffled_list(orig_lst):
    new_list = orig_lst.copy()
    shuffle(new_list)
    return new_list


orig_lst = [1, 2, 3, 4, 5]

node1_lst = get_shuffled_list(orig_lst)
node2_lst = get_shuffled_list(orig_lst)

print(node1_lst)
print(node2_lst)

Output:

[5, 4, 1, 2, 3]
[1, 4, 5, 2, 3]
Sagar Gupta
  • 1,352
  • 1
  • 12
  • 26
2

since chef uses ruby, you can use ruby code in your recipes and shuffling an array in ruby is builtin into the ruby core.

a = [ 1, 2, 3 ]           #=> [1, 2, 3]
a.shuffle                 #=> [2, 3, 1]
a                         #=> [1, 2, 3]

in chef, you can might want to use ruby_block resource and use ruby within it or assign the suffled list to a node attribute and reference this node attribute within your recipes.

Mr.
  • 9,429
  • 13
  • 58
  • 82