为什么通知任务没有在ansible中执行?

Ahs*_*que 5 ansible ansible-playbook ansible-2.x

我面临的问题很常见,但其他解决方案对我不起作用.正如问题所示,当我运行我的Playbook时,只有第一个通知处理程序被执行.即仅重新启动firewalld,但未获取更新的bash配置文件.

有些人建议通知链接,但我不想将两个任务合并为完全不同的目标.例如,一个任务可能是将端口添加到firewalld然后重新启动它; 另一个可以更新我的bash配置文件以显示history命令输出的日期.

NB上面的代码片段不是我的完整.yml,只是其中的一部分,所以这可能会也可能不会起作用.但是,原始文件确实有效.

---
  tasks  
   - name: add port-80 to firewalld
     firewalld: zone=drop port=80/tcp permanent=true state=enabled

   - name: add port-443 to firewalld
     firewalld: zone=drop port=443/tcp permanent=true state=enabled

   - shell: firewall-cmd --reload
     notify:
      - Restart firewalld

   - name: Enabling time display in history
     blockinfile:
     dest: ~/.bash_profile
     block: |
         export HISTTIMEFORMAT="%d/%m/%y %T "
     notify:
      - Source the updated Bash profile


  handlers:
   - name: Restart firewalld
     service: name=firewalld state=restarted

   - name: Source the updated Bash profile
     shell: source ~/.bash_profile

...
Run Code Online (Sandbox Code Playgroud)

Ahs*_*que 10

最后,我在评论的帮助下找出了问题所在.

当且仅当状态是changed任务的结果时,才会执行通知处理程序.

我正在做的错误是尝试安装已安装的软件包.所以,国家没有改变.

让我们看一个例子,

---
- hosts: varnish
  remote_user: root

  tasks:    
   - name: Install tree
     yum: name=tree state=absent
     notify:
      - Do an echo

  handlers:
   - name: Do an echo
     debug: msg="This will be printed"    
...
Run Code Online (Sandbox Code Playgroud)

我们将两次运行剧本.

首次运行后,我们将获得:

TASK [Install tree] ************************************************************
changed: [192.***.***.**]

RUNNING HANDLER [Do an echo] ***************************************************
ok: [192.***.***.**] => {
    "msg": "This will be printed"
}

PLAY RECAP *********************************************************************
192.***.***.**             : ok=1    changed=1    unreachable=0    failed=0   
Run Code Online (Sandbox Code Playgroud)

随着状态的改变(查看changed=1部件),将打印调试消息.

第二次运行后,我们将获得:

TASK [Install tree] ************************************************************
ok: [192.***.***.**]

PLAY RECAP *********************************************************************
192.***.***.**             : ok=0    changed=0    unreachable=0    failed=0   
Run Code Online (Sandbox Code Playgroud)

要注意的是不像第一次运行那样调用处理程序,因为状态在第二次运行中没有改变(树已经安装).

我已将其作为答案发布,它可能有助于其他用户.

  • 好答案.调试时,将"changed_when:true"添加到发出通知的任务中,强制更改状态会很有用. (4认同)