Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage whole crontab files in Ansible

Tags:

cron

ansible

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?

like image 476
Ale Avatar asked Jun 02 '15 15:06

Ale


3 Answers

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.

like image 120
Ralph Bolton Avatar answered Oct 16 '22 11:10

Ralph Bolton


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
like image 25
Ale Avatar answered Oct 16 '22 12:10

Ale


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
like image 37
Phil Avatar answered Oct 16 '22 11:10

Phil