Ansible处理程序仅在changed为true时运行。

7

使用Ansible安装ntp,我会通知处理程序以启动ntpd服务:
任务:

---
# roles/common/tasks/ntp.yml
  - name: ntp | installing
    yum: name=ntp state=latest
    notify: start ntp

处理程序:

---
# roles/common/handlers/main.yml

- name: start ntp
  service: name=ntpd state=started

如果服务尚未安装,Ansible 将安装并启动它。
如果服务已经安装,但没有运行,它不会通知处理程序:
任务的状态为 changed: false
这意味着,如果服务已经存在于操作系统中,则无法启动它。
有什么好的实践可以确保服务已安装并处于运行状态吗?
PS:我可以这样做:
---
# roles/common/tasks/ntp.yml
  - name: ntp | installing
    yum: name=ntp state=latest
    notify: start ntp
    changed: true

但我不确定这是否是一个好的做法。

2个回答

12

Playbooks入门指南中可以看到:

正如我们提到的那样,模块被编写为“幂等”的,并且可以在远程系统上进行更改时进行传递。Playbooks意识到这一点,并具有基本事件系统,可用于响应更改。

这些“通知”操作在playbook中每个任务块的末尾触发,并且即使被多个不同任务通知也只会触发一次。

处理程序(Handlers)是按设计仅在更改时运行的。如果要更改配置,则通常需要重新启动服务,但是如果没有更改则不希望重新启动。

您所需的是:如果服务尚未运行,则启动服务。要执行此操作,应像@udondan所描述的那样使用常规任务。

- name: ntp | installing
  yum:
    name: ntp
    state: latest

- name: ntp | starting
  service:
    name: ntpd
    state: started
    enabled: yes

Ansible 的设计是幂等的,因此仅当 ntp 尚未运行时才运行第二个任务。 enabled 行将设置服务在启动时启动。 如果不需要此行为,请删除此行。


6
为什么不添加一个服务任务呢?通常,处理程序用于在配置更改后重新启动服务。为了确保无论如何都能运行服务,请添加类似以下的任务:
- name: Ensure ntp is running
  service:
    name: ntpd
    state: started

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接