Remove CRON entry not created with Ansible

Via Ansible, is there any way to remove a CRON job entry that was not created by Ansible? For example, I have the entry below, but as you can see, it does not have the ansible above it, so it does not have a “name” parameter to remove.

4 3 * * * /sbin/shutdown -r now >/dev/null 2>&1

No. You’d have to resort to some shell workaround, for example:

grep -v /sbin/shutdown | crontab -

> Via Ansible, is there any way to remove a CRON job entry that was not
> created by Ansible? For example, I have the entry below, but as you can
> see, it does not have the ansible above it, so it does not have a "name"
> parameter to remove.
>
> 4 3 * * * /sbin/shutdown -r now >/dev/null 2>&1

Put the entries into a dictionary and test it in scratch first

    my_cron:
      cron_file: /scratch/crontab
      user: admin
      entries:
        - name: shutdown
          state: present
          disabled: false
          minute: 4
          hour: 3
          job: '/sbin/shutdown -r now >/dev/null 2>&1'

Given the file

  > cat /scratch/crontab
  4 3 * * * admin /sbin/shutdown -r now >/dev/null 2>&1

add the descriptions of the crontab entries, e.g.

    - lineinfile:
        path: "{{ my_cron.cron_file }}"
        line: '#Ansible: {{ item.name }}'
        regexp: '^#Ansible: {{ item.name }}$'
        insertbefore: '{{ item.job }}'
      loop: "{{ my_cron.entries }}"
      when: not item.disabled

The description was added to the crontab

  > cat /scratch/crontab
  #Ansible: shutdown
  4 3 * * * admin /sbin/shutdown -r now >/dev/null 2>&1

Now, if you disable the entry

    my_cron:
      cron_file: /scratch/crontab
      user: admin
      entries:
        - name: shutdown
          state: present
          disabled: true
          minute: 4
          hour: 3
          job: '/sbin/shutdown -r now >/dev/null 2>&1'

the *cron* module works as expected

    - cron:
        cron_file: "{{ my_cron.cron_file }}"
        user: "{{ my_cron.user }}"
        state: "{{ item.state|d('present') }}"
        disabled: "{{ item.disabled|d(false) }}"
        name: "{{ item.name }}"
        job: "{{ item.job }}"
        minute: "{{ item.minute|d(omit) }}"
        hour: "{{ item.hour|d(omit) }}"
        day: "{{ item.day|d(omit) }}"
        month: "{{ item.month|d(omit) }}"
        weekday: "{{ item.weekday|d(omit) }}"
      loop: "{{ my_cron.entries }}"

and disables the entry in the crontab

  > cat /scratch/crontab
  #Ansible: shutdown
  #4 3 * * * admin /sbin/shutdown -r now >/dev/null 2>&1

These two tasks are idempotent. You'll have to run such playbook
twice, at least for the first time to add missing descriptions to
enabled items. Then you can keep the *lineinfile* task in the playbook
to make sure the descriptions are present.