Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Ansible to generate a hashing number from a string?

Tags:

ansible

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 }}

like image 761
MagMax Avatar asked Nov 26 '25 18:11

MagMax


1 Answers

{{ ( inventory_hostname | hash('sha256') | int(0, 16) ) % 59 }}
like image 101
Rob Avatar answered Dec 01 '25 09:12

Rob