在 Ansible 中管理整个 crontab 文件
Manage whole crontab files in Ansible
我在服务器上有一个包含大约 80 个条目的 crontab。我想使用 Ansible 管理那个 crontab。
理想情况下,我会将服务器的 crontab 复制到我的 Ansible 目录并创建一个 Ansible 任务以确保在服务器上设置 crontab。
但是 cron module 似乎只管理单个 cron 条目而不是整个 crontab 文件。
手动将 crontab 迁移到 Ansible 任务很繁琐。即使我找到或制作了一个自动执行此操作的工具,我也觉得 YAML 文件的可读性远不如 crontab 文件。
知道如何使用 Ansible 处理那个大的 crontab 吗?
我设法找到了一种简单的方法来做到这一点。我将 crontab 文件复制到服务器,然后在文件更改时使用 shell 模块更新 crontab。
crontab 任务:
---
- name: Ensure crontab file is up-to-date.
copy: src=tasks/crontab/files/{{ file }} dest={{ home }}/cronfile
register: result
- name: Ensure crontab file is active.
shell: crontab cronfile
when: result|changed
在我的剧本中:
- include: tasks/crontab/main.yml file=backend.cron
我是这样解决这个问题的:
- name: Save out Crontabs
copy: src=../files/crontabs/{{ item }} dest=/var/spool/cron/{{ item }} owner={{item}} mode=0600
notify: restart cron
with_items:
- root
- ralph
- jim
- bob
这种方法(相对于写入中间文件)的优势在于,实时 crontab 的任何手动编辑都将被删除并替换为 Ansible 受控版本。缺点是它有点破坏了 cron 进程。
通过这种方式保持幂等性:
- name: crontab
block:
- name: copy crontab file
copy:
src: /data/vendor/home/cronfile
dest: /home/mule/cronfile
mode: '0644'
register: result
- name: ensure crontab file is active
command: crontab /home/mule/cronfile
when: result.changed
rescue:
- name: delete crontab file
file:
state: absent
path: /home/mule/cronfile
我在服务器上有一个包含大约 80 个条目的 crontab。我想使用 Ansible 管理那个 crontab。
理想情况下,我会将服务器的 crontab 复制到我的 Ansible 目录并创建一个 Ansible 任务以确保在服务器上设置 crontab。
但是 cron module 似乎只管理单个 cron 条目而不是整个 crontab 文件。
手动将 crontab 迁移到 Ansible 任务很繁琐。即使我找到或制作了一个自动执行此操作的工具,我也觉得 YAML 文件的可读性远不如 crontab 文件。
知道如何使用 Ansible 处理那个大的 crontab 吗?
我设法找到了一种简单的方法来做到这一点。我将 crontab 文件复制到服务器,然后在文件更改时使用 shell 模块更新 crontab。
crontab 任务:
---
- name: Ensure crontab file is up-to-date.
copy: src=tasks/crontab/files/{{ file }} dest={{ home }}/cronfile
register: result
- name: Ensure crontab file is active.
shell: crontab cronfile
when: result|changed
在我的剧本中:
- include: tasks/crontab/main.yml file=backend.cron
我是这样解决这个问题的:
- name: Save out Crontabs
copy: src=../files/crontabs/{{ item }} dest=/var/spool/cron/{{ item }} owner={{item}} mode=0600
notify: restart cron
with_items:
- root
- ralph
- jim
- bob
这种方法(相对于写入中间文件)的优势在于,实时 crontab 的任何手动编辑都将被删除并替换为 Ansible 受控版本。缺点是它有点破坏了 cron 进程。
通过这种方式保持幂等性:
- name: crontab
block:
- name: copy crontab file
copy:
src: /data/vendor/home/cronfile
dest: /home/mule/cronfile
mode: '0644'
register: result
- name: ensure crontab file is active
command: crontab /home/mule/cronfile
when: result.changed
rescue:
- name: delete crontab file
file:
state: absent
path: /home/mule/cronfile