【问题标题】:How to delete a cron job with Ansible?如何使用 Ansible 删除 cron 作业?
【发布时间】:2015-10-21 09:11:22
【问题描述】:

我有大约 50 台 Debian Linux 服务器,它们的 cron 任务很糟糕:

0 * * * * ntpdate 10.20.0.1

我想用 ntpd 配置 ntp 同步,所以我需要删除这个 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 作业?

【问题讨论】:

    标签: linux debian ansible


    【解决方案1】:

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

    Crontab 是用于安装、删除或列出用于驱动 cron(8) 守护程序的表的程序。每个用户都可以有自己的 crontab,虽然这些是 /var/spool/ 中的文件,但它们并不打算直接编辑。对于 mls 模式下的 SELinux,每个范围可以有更多的 crontabs。更多内容请参见 selinux(8)。

    正如手册页和上面的引用中提到的,您不应该直接编辑/使用这些文件,而应该使用可用的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 模块。

    【讨论】:

    • 值得注意的是,如果用户没有 crontab,crontab -r 将返回退出代码 1。 ignore_errors: yes 可能有用。
    猜你喜欢
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2013-08-04
    • 2013-03-27
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多