Reputation: 5
Need some expertise help,
I'm trying to see if there is a way to randomly pick a attribute from an array doing a chef client run.
Example, I have this attribute
default['collectors_a'] = { a, b, c, d, e}
and In the recipe I want to randomly choose one of this element from the array.
Does anyone know how to go about it?
Thanks so much for helping out!!!!
Upvotes: 0
Views: 167
Reputation: 54251
So a few issues, {...}
is for a Hash, not an Array. In Ruby an Array literal looks like [...]
, like [1, 2, 3]
or ["a", "b", "c"]
. With that said, there is a method on the Array object to help with this, Array#sample
will return a random object from the array. So you might want something like ["a", "b", "c"].sample
. However remember that this will re-roll the selection every time Chef runs which is almost never what you want. If you want something randomized per server but consistent you could do this instead:
vals = ["a", "b", "c"]
default["whatever"] = vals[node["shard_seed"] % vals.length]
The shard_seed
attribute comes from Ohai and is a consistent hash based on a number of inputs like the CPU ID and machine UUID.
Upvotes: 1