In order to generate random cron executions for each host, I'd like to randomize the hour when it is going to be executed, to spread the load and avoid all hosts to run hard tasks at the same time.
So, if it would be possible to generate a different hour and minute for each host, it would spread it automatically.
Example:
cron:
name: "Conquer the world"
minute: "{{ ansible.hostname | str2num(0, 59) }}"
hour: "{{ ansible.hostname | str2num(4, 6) }}"
job: "conquer_the_world.sh"
Wanted function is what I named str2num, that should generate the same number for the same host in a deterministic way, and may be different for each host.
Is already there any solution for this or should I create a custom filter for this?
ANSWER
I finally found the answer by myself, thanks to the blog post: https://ansibledaily.com/idempotent-random-number/:
cron:
name: "Conquer the world"
minute: "{{ (59 |random(seed=ansible_hostname)) }}"
hour: "{{ (2 |random(seed=ansible_hostname)) + 4 }}"
job: "conquer_the_world.sh"
In general: {{ ( (MAX - MIN) | random(seed=ansible_hostname)) + MIN }}
{{ ( inventory_hostname | hash('sha256') | int(0, 16) ) % 59 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With