Salting Random Crons

So you want to create a random cron, with Salt… here’s how:

    - name: /usr/bin/someCronScript
    - minute: {{ range(0,59,1)|random }}
    - hour: {{ range(0,23,1)|random }}

That lovely snippet will create a cron that runs daily at a random hour and random minute. They are statically added to the crontab, but they are assigned randomly.

What we have here is a declaration that runs cron.present and sets the parameters name, minute, and hour.

name is the line that is executed when the cron fires

minute is passed some jinja {{ range(0,59,1)|random }}

Let’s break that down further. Inside the mustaches ({{) we use the range function range() which takes 3 parameters. The first is the starting number, here we have 0. The second is the ending number, we have 59. The third parameter is optional and takes the step of the range. We have selected 1, which is the default. This gives us a range of numbers from 0 to 59. Finally we pass that through the filter random, which picks one of the numbers are random.

We repeat this process for hour but with 0 through 23 for the hours of the day.

Finally cron.present will give us a * for the other cron times.

We are provided with (something similiar to) the following in our cron tab:

17 13 * * * /usr/bin/someCronScript

And that is how you assign a random cron time with Salt.