linux - 如何使用 Ansible 删除 cron 作业?

标签 linux debian ansible

我有大约 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 作业?

最佳答案

用户的 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).

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

关于linux - 如何使用 Ansible 删除 cron 作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33255249/

相关文章:

Ansible:将注册变量保存到文件

linux - 如何使用rsync对大文件(100GB)进行增量备份?

linux - 尝试汇编 IA32 汇编文件并收到 'call' 的操作数不匹配错误

linux - 在 Linux/Sublime 上的所有文件中搜索未注释的字符串

vim - Vim启动错误(表达式无效)Debian

azure - 如何使用 ansible 在 azure 上创建实例并安装软件包

Ansible如何在jinja2模板中引用项目

python - 在一个 Linux 发行版上构建 Python 包并从另一个发行版运行它们

Django gunicorn Nginx 设置仅显示 404 页面

php - 在 Debian 中使用 pthreads 编译 PHP