ansible comment multiple cron jobs

Viewed 1459

I have the following task which works in the sense that it comments the desired jobs (job1 to job5) from user's crontab, but what bugs me is that , actually the play appends the jobs and does not replace them.


- name: "Comment  cron jobs"
    cron:
      user: "{{ ansible_env.USER }}"
      name: "Comment"
      job: "{{ item }}"
      state: present
      disabled: True
    with_items:
      - 'job1'
      - 'job2'
      - 'job3'
      - 'job4'
      - 'job5'
    tags: stop_cronn

This is the result of crontab -l. I want to replace them not to append them .


* * * * *  job1
* * * * *  job2
* * * * *  job3
* * * * *  job4
*/5 * * * *  job5

#Ansible: None
#* * * * * job1
#Ansible: None
#* * * * * job2
#Ansible: None
#* * * * * job3
#Ansible: None
#* * * * *  job4
#Ansible: None
#* * * * *  job5

I'm using ansible 2.4.2.0 . Thx

1 Answers

As per doc - https://docs.ansible.com/ansible/latest/collections/ansible/builtin/cron_module.html

When crontab jobs are managed: the module includes one line with the description of the crontab entry "#Ansible: " corresponding to the “name” passed to the module, which is used by future ansible/module calls to find/check the state. The “name” parameter should be unique, and changing the “name” value will result in a new cron task being created (or a different one being removed).

Also regarding name parameter:

Note that if name is not set and state=present, then a new crontab entry will always be created, regardless of existing ones.

So in your case you have 5 jobs with non-unique names, which means ansible can't properly manage your records. You need to rewrite your task as something like:


- name: "Comment  cron jobs"
    cron:
      user: "{{ ansible_env.USER }}"
      name: "{{ item.name }}"
      job: "{{ item.job }}"
      state: present
      disabled: True
    loop:
      - { job: 'job1', name: "job1 name" }
      - { job: 'job2', name: "job2 name" }
    tags: stop_cronn

If you want to manage existing records - ansible can't do that as outlined earlier, you have to specify unique name and #Ansible comment should exist.

Related