来自调试信息时的条件

问题描述

我想从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   

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...