ansible 评论多个 cron 作业

ansible comment multiple cron jobs

我有以下任务,它从用户的 crontab 评论所需的工作(job1 到 job5),但让我感到困扰的是,实际上该游戏附加了这些工作而不是替换它们。


- 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

这是crontab -l的结果。我想替换它们而不是附加它们。


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

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

我正在使用 ansible 2.4.2.0。谢谢

根据文档 - 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).

另外关于 name 参数:

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

因此,在您的情况下,您有 5 个工作名称为 non-unique,这意味着 ansible 无法正确管理您的记录。您需要将您的任务重写为:


- 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

如果您想管理现有记录 - ansible 无法如前所述执行此操作,您必须指定唯一名称并且 #Ansible 评论应该存在。