问题描述
我想从stdout创建一个when条件的任务。 剧本示例:
---
- hosts: localhost
gather_facts: false
ignore_errors: yes
vars:
- dev_ip: '192.168.20.192'
tasks:
- name: checkking ssh status
wait_for:
host: "{{dev_ip}}"
port: 22
timeout: 2
state: present
register: ssh_stat
- name: checkcondition
debug:
msg: "{{ssh_stat}}"
输出的消息是:
ok: [localhost] => {
"msg": {
"changed": false,"elapsed": 2,"failed": true,"msg": "Timeout when waiting for 192.168.20.192:22"
}
}
如果要在字符串ssh_stat.stdout中输入“等待192.168.20.192:22时超时”,我想做一个条件任务。
解决方法
这是您需要的:
---
- name: answer stack overflow
hosts: localhost
gather_facts: false
ignore_errors: yes
tasks:
- name: checkking ssh status
wait_for:
host: 192.168.1.23
port: 22
timeout: 2
state: present
register: ssh_stat
- name: do something else when ssh_stat.msg == "Timeout when waiting for 192.168.1.23:22"
shell: echo "I am doing it"
when: ssh_stat.msg == "Timeout when waiting for 192.168.1.23:22"
输出:
PLAY [answer stack overflow] **************************************************************************************************************************************************************************************
TASK [checkking ssh status] ***************************************************************************************************************************************************************************************
[WARNING]: Platform linux on host localhost is using the discovered Python interpreter at /usr/bin/python,but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
fatal: [localhost]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": false,"elapsed": 3,"msg": "Timeout when waiting for 192.168.1.23:22"}
...ignoring
TASK [do something else when ssh_stat.msg == "Timeout when waiting for 192.168.1.23:22"] ************************************************************************************************************************
changed: [localhost]
PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1