Manage whole crontab files in Ansible

Maintain idempotency by doing it this way:

- name: crontab
  block:
    - name: copy crontab file
      copy:
        src: /data/vendor/home/cronfile
        dest: /home/mule/cronfile
        mode: '0644'
      register: result

    - name: ensure crontab file is active
      command: crontab /home/mule/cronfile
      when: result.changed

  rescue:
    - name: delete crontab file
      file:
        state: absent
        path: /home/mule/cronfile

I solved this problem like this:

- name: Save out Crontabs
  copy: src=../files/crontabs/{{ item }} dest=/var/spool/cron/{{ item }} owner={{item}} mode=0600
  notify: restart cron
  with_items:
  - root
  - ralph
  - jim
  - bob

The advantage of this method (versus writing to an intermediate file) is that any manual edits of the live crontab get removed and replaced with the Ansible controlled version. The disadvantage is that it's somewhat hacking the cron process.


I managed to find a simple way to do it. I copy the crontab file to the server and then update the crontab with the shell module if the file changed.

The crontab task:

---
- name: Ensure crontab file is up-to-date.
  copy: src=tasks/crontab/files/{{ file }} dest={{ home }}/cronfile
  register: result
- name: Ensure crontab file is active.
  shell: crontab cronfile
  when: result|changed

In my playbook:

- include: tasks/crontab/main.yml file=backend.cron

Tags:

Cron

Ansible