繁体   English   中英

使用 Ansible 删除 cron

[英]Remove cron using Ansible

我正在尝试从所有节点中删除 cron 作业。 Ansible 脚本运行没有任何错误,但它不会删除 cron。

这是我的剧本

---
- hosts: all
  user: <user_name>
  tasks:
  - name: disable cron
    cron:
      name: clean
      env: yes
      state: absent
      user: root
    become: True

这是我在目标主机上的 cron。

[root@host1]# crontab -l

#Ansible: None
*/5 * * * * /root/cleanup.sh

#Ansible: None
*/5 * * * * /root/cleanup.sh

#Ansible: clean
*/5 * * * * /root/cleanup.sh

我尝试将 name 替换为NoneAnsible: None#Ansible: Noneclean 他们都没有工作。

如何删除此 cron? 看起来幂等性不适用于 ansible 中的 cron 模块,因为我运行了两次放置 cron 并且它放置了两次 cronjob。

这对我有用(都添加 cron 条目作为删除):

- name: Enforce cron entries in variable files
  hosts: all
  become: true
  become_user: wls

  tasks:
  - name: "enforce crontab entries"
    cron:
      name: "{{ item.name }}"
      minute: "{{ item.minute| default('') }}"
      hour: "{{ item.hour| default('') }}"
      job: "{{ item.job| default('') }}"
      state: "{{ state | default('present') }}"
    loop: "{{ crontabentries }}"
    when:
    - crontabentries is defined
    - crontabentries| length > 0
    - item.state|default('present')  != 'absent'

  - name: enforce absence of entries
    cron:
      name: "{{ item.name }}"
      state: absent
    loop: "{{ crontabentries }}"
    when:
    - crontabentries is defined
    - crontabentries| length > 0
    - item.state|default('present')  == 'absent'

带有要删除的变量文件:

crontabentries:
-  name: "somecronjob"
   state: absent

或要添加的变量文件:(状态 = 默认情况下存在,因此无需提及)

crontabentries:
-  name: "somecronjob"
   minute: "0"
   hour: "6"
   job: "find /var/log/*.log -mtime +30 -type f -delete"

定义env您要求删除环境变量。

- name: disable cron
  cron:
    name: clean
    state: absent
    user: root
  become: True

看起来幂等性不适用于 Ansible 中的 cron 模块

它工作正常,所以检查你的代码。 如果你有问题,你可以随时在 SO 上提出另一个问题,但你需要包含代码。

我为我尝试了以下工作:

 ---
 - hosts: test
   become: true
   become_user: root
   any_errors_fatal: false
   tasks:

   - name: disable cron
     cron:
      name: "{{ item }}"
      state: absent
      user: root
      become: True
      with_items:
       - clean
       - None
       - None

我已经通过试运行检查过它:ansible-playbook cronclean.yml --check

O/P 为: 在此处输入图片说明

如果您有非常复杂的 crontab 条目,您也可以通过 ansible 的 shell 模块将其删除,如下例所示。

---
- name: Deleting contab entry
  hosts: ecx
  become: true
  tasks:
   - name: "decroning entry"
     shell:
           "crontab -l -u root |grep -v mybot  |crontab -u root -"
     register: cronout
   - debug: msg="{{cronout.stdout_lines}}" 

说明:- 您只需将第 8 行的"mybot"字符串替换为您的 crontab 条目的唯一标识。 而已。 对于“ how to delete multiple crontab entries by ansible ”,您可以在grep中使用多个字符串,如下所示

"crontab -l -u root |grep -v 'strin1\|string2\|string3\|string4'  |crontab -u root -"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM