ansible - Ansible 处理程序和条件
问题描述
我试图找到一个逻辑来检查服务是否正在运行,如果没有运行,则启动它。下面是我写的逻辑,但由于某种原因,通知没有调用处理程序?
---
- name: Executing the play to start the service
hosts: nodes
become: yes
gather_facts: False
tasks:
- name: Executing the Shell task to check the status of the wso2 instance
shell: myMsg=$(sudo service wso2esb status| grep Active | awk '{print $3}');if [[ $myMsg == "(dead)" ]]; then echo "Not Running";else echo "Running";fi
ignore_errors: yes
register: result
notify: handl
when: result.stdout == "Not Running" (I even tried 'changed_when', but the same error)
handlers:
- name: handl
service: name=wso2esb state=started
$ ansible-playbook -i inventories/hosts.sit start.yml -b -k
SSH password:
PLAY [Executing the play to start the wso2 service] ***********************************************
TASK [Executing the Shell task to check the status of the instance] *******************************
fatal: [mpstest01]: FAILED! => {"msg": "The conditional check 'result.stdout == \"Not Running\"' failed. The error was: error while evaluating conditional (result.stdout == \"Not Running\"): **'result' is undefined**\n\nThe error appears to have been in '/home/ansible1/start.yml': line 9, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: Executing the Shell task to check the status of the instance\n ^ here\n"}
...ignoring
PLAY RECAP ****************************************************************************************
mpstest01 : ok=1 changed=0 unreachable=0 failed=0
解决方案
这一切似乎都是不必要的。您不需要“检查服务是否正在运行,如果未运行,则启动它”;这正是服务模块所做的。只需将service
模块放入任务中,不要打扰处理程序:
- name: start service if it isn't already running
service: name=wso2esb state=started
虽然我更喜欢 YAML 语法而不是 key=value 语法:
- name: start service if it isn't already running
service:
name: wso2esb
state: started
在任何情况下,service
模块都会检查服务是否正在运行,如果没有,它将启动它。