Linux – Ansible: Run cron at different times on each host

Ansible: Run cron at different times on each host… here is a solution to the problem.

Ansible: Run cron at different times on each host

I need to configure a cron job to run at different times on multiple hosts.
Ideally, I would like to have an index that identifies the host I’m currently modifying and offsets it.

So if I run ansible against :

HOSTA
HOSTB
HOSTC

I want to configure cron like this

0 1 * * * #HOSTA
0 2 * * * #HOSTB
0 3 * * * #HOSTC

Do you know how I can implement it without hard-coding variables for each host?

Solution

You can use with_items loops on dictionary arrays. Then use inventory_hostname or ansible_hostname to filter the appropriate items:

- name: cron jobs
  cron: min=0 hour={{ item.h }} job="echo server {{ item.s }} cron job started" state=present
  when: inventory_hostname == item.s
  with_items:
  - { s: 'hosta', h: 1 }
  - { s: 'hostb', h: 2 }
  - { s: 'hostc', h: 3 }

Related Problems and Solutions