如何使用 Ansible 删除 cron 作业?

How to delete a cron job with Ansible?

我有大约 50 台 Debian Linux 服务器的 cron 作业不佳:

0 * * * * ntpdate 10.20.0.1

我想配置 ntp 与 ntpd 同步,所以我需要删除这个 cron 作业。对于配置,我使用 Ansible。我试图用这个游戏删除 cron 条目:

tasks:
   - cron: name="ntpdate" minute="0" job="ntpdate 10.20.0.1" state=absent user="root"

什么都没发生。

那我运行这部剧:

tasks:
   - cron: name="ntpdate" minute="0" job="ntpdate pool.ntp.org" state=present

我在 "crontab -l" 的输出中看到新的 cron 作业:

...
# m h  dom mon dow   command
  0 *  *   *   *     ntpdate 10.20.0.1
#Ansible: ntpdate
0 * * * * ntpdate pool.ntp.org

但是/etc/cron.d是空的!我不明白 Ansible cron 模块是如何工作的。

如何使用 Ansible 的 cron 模块删除我手动配置的 cron 作业?

用户的 crontab 条目保存在 /var/spool/cron/crontab/$USER 下,如 crontab man page 中所述:

Crontab is the program used to install, remove or list the tables used to drive the cron(8) daemon. Each user can have their own crontab, and though these are files in /var/spool/ , they are not intended to be edited directly. For SELinux in mls mode can be even more crontabs - for each range. For more see selinux(8).

如手册页和上述引文中所述,您不应直接 editing/using 这些文件,而应使用可用的 crontab 命令,例如 crontab -l 来列出用户的 crontab 条目,crontab -r 删除用户的 crontab 或 crontab -e 编辑用户的 crontab 条目。

要手动删除 crontab 条目,您可以使用 crontab -r 删除所有用户的 crontab 条目或 crontab -e 直接编辑 crontab。

对于 Ansible,这可以通过使用 cron 模块的 state: absent 来完成,如下所示:

hosts : all
tasks :
  - name : remove ntpdate cron entry
    cron :
      name  : ntpdate
      state : absent

然而,这依赖于 Ansible 放在 crontab 条目上方的注释,可以从这个简单的任务中看到:

hosts : all
tasks :
  - name : add crontab test entry
    cron :
      name  : crontab test
      job   : echo 'Testing!' > /var/log/crontest.log
      state : present

然后设置一个 crontab 条目,如下所示:

#Ansible: crontab test
* * * * * echo Testing > /var/log/crontest.log

不幸的是,如果您在 Ansible 的 cron 模块之外设置了 crontab 条目,那么您将不得不采取不太干净的方法来整理您的 crontab 条目。

为此,我们只需使用 crontab -r 丢弃用户的 crontab,我们可以通过 shell 调用它,如下所示:

hosts : all
tasks :
  - name  : remove user's crontab
    shell : crontab -r

然后我们可以使用进一步的任务来设置您想要保留或添加的任务,正确使用 Ansible 的 cron 模块。