9
votes

I have a crontab containing around 80 entries on a server. And I would like to manage that crontab using Ansible.

Ideally I would copy the server's crontab to my Ansible directory and create an Ansible task to ensure that crontab is set on the server.

But the cron module only seems to manage individual cron entries and not whole crontab files.

Manually migrating the crontab to Ansible tasks is tedious. And even if I find or make a tool that does it automatically, I feel the YAML file will be far less readable than the crontab file.

Any idea how I can handle that big crontab using Ansible?

3
Just use the copy module to copy the crontab to the appropriate location?larsks
I do not have root privileges.Ale
Maybe use docs.ansible.com/assemble_module.html? If you don't have root, how are you going to modify crontab anyway?Mxx
A user does not need root privileges to update his crontab.Ale

3 Answers

13
votes

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
1
votes

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.

1
votes

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