Idempotency and Random Variables in Ansible

Is there a way to guarantee idempotency for players using randomly generated variables?

For example, I want to configure my crontabs to run emails on multiple servers at different times, so I create random integers using one set_fact module:

tasks: - set_fact: first_run_30="{{ 30 | random }}" run_once: yes 

Then apply these generated variables to my crontab using these features:

  - name: Setup cron30job cron: name=cron30job minute={{first_run_30}},{{first_run_30 | int + 30}} job='/bin/bash /cron30job.sh' state=present user=root environment: MAILTO: ' me@somelist.com ' MAILFROM: ' me@somehost.com ' 

This works very well, however, in my opinion, this principle of unacceptable purity is violated using this strategy, because every time a game occurs, you see a change:

 TASK: [Setup cron30job] ***************************************** changed: [127.0.0.1] 

In addition, in crontab checking as root each time for three separate runs:

 [ansible]# cat /var/spool/cron/root #Ansible: cron30job 5,35 * * * * /bin/bash /sw/test/cron30job.sh #Ansible: cron30job 9,39 * * * * /bin/bash /sw/test/cron30job.sh #Ansible: cron30job 6,36 * * * * /bin/bash /sw/test/cron30job.sh 

If there is a workaround, or perhaps in my scenario it may be irreversibly implausible, I would like to know.

+5
source share
2 answers

Instead of a random value, you can get something related to node as a hash of the host name or the last byte of the ip address.

This is an example:

 - name: Get a pseudo-random minute shell: expr $((16#`echo "{{inventory_hostname}}" | md5sum | cut -c 1-4`)) % 30 register: minute changed_when: false 
+6
source

Compared to version 2.3, it is possible to initialize a random number generator from a seed. This way you can create random but idempotent numbers:

 "{{ 59 |random(seed=inventory_hostname) }} * * * * root /script/from/cron" 

Source: Random Number Filter

I used this template to create a random cron start time with:

  • different minutes on different target servers
  • different minutes for different hours on the same server (random)
  • at the same minute on the same day and the server when you restart Ansible (idempotence)

Requires Ansible> = 2.3:

  cron: name: "{{some_name}}_{{item.day}}" state: present job: "{{some_job}}" weekday: "{{item.day}}" hour: "{{item.hour}}" minute: "{{59|random(seed=inventory_hostname + item.dow)}}" with_items: - { day: 0, hour: 3, dow: "sunday" } - { day: 1, hour: 7, dow: "monday" } - { day: 2, hour: 1, dow: "tuesday" } - { day: 3, hour: 5, dow: "wednesday" } - { day: 4, hour: 2, dow: "thursday" } - { day: 5, hour: 4, dow: "friday" } - { day: 6, hour: 7, dow: "saturday" } 
+6
source

Source: https://habr.com/ru/post/1234641/


All Articles