使用 if 语句的 Ansible 处理程序

标签 ansible ansible-handlers

我有一个 apache playbook,需要在 centos 7 和 centos 6 上运行。我希望根据发行版主要版本触发处理程序。我有一个名为 restart apache on 7 的处理程序,还有一个名为 restart apache on 6 的处理程序。

我的handlers/main.yml看起来像这样

 ---
 - name: restart apache on 7
  systemd: name=httpd state=restarted

 - name: restart apache on 6
   service: name=httpd state=restarted

我尝试在 tasks/main.yml 中执行以下操作,但似乎遇到了与通知脚本相关的语法问题。

- name: Copy custom configs
  copy:
   dest: /etc/httpd/conf/
   src: httpd.conf
   owner: root 
  notify: {%if ansible_distribution_major_version >= '7.0' %}restart apache on 7 {%else%} restart apache on 6 {%endif%}

有关如何编写通知语句以实现我的目标的任何线索吗?

最佳答案

对于通用解决方案,您可以使用 topics ,但我不确定您为什么要使用 systemd 模块而不是 service - 后者应该涵盖 CentOS 6 和 7,没有任何区别。

还对 ansible_distribution_major_version 使用算术比较,而不是示例中的字符串比较。


监听主题的处理程序:

---
- name: restart apache on 7
  systemd: name=httpd state=restarted
  when: ansible_distribution_major_version >= 7
  listen: "restart apache"

- name: restart apache on 6
  service: name=httpd state=restarted
  when: ansible_distribution_major_version < 7
  listen: "restart apache"

以及通知他们的任务:

- name: Copy custom configs
  copy:
    dest: /etc/httpd/conf/
    src: httpd.conf
    owner: root 
  notify: "restart apache"

关于使用 if 语句的 Ansible 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43169426/

相关文章:

global-variables - 如何在任务中获取当前角色名称

Ansible 循环错误

ansible - 如何在 Ansible 中执行任务之前强制运行处理程序?

ansible - 整个剧本仅运行一次Ansible处理程序

shell - 让 ansible 在没有退出代码停止 ssh 连接的情况下运行脚本

python - 通过 dict 变量到 stat 模块的路径

ansible - 为 Ansible 指定 sudo 密码

使用 group_by 时 Ansible 将看不到处理程序

ansible - 仅在需要时使用处理程序执行 Ansible 重启