Ansible中基于条件的执行

时间:2019-05-03 05:21:29

标签: ansible return-value

如果第一个条件成功,则执行第二个条件;如果第二个条件成功,则执行第三个条件。

下面是我尝试过的。

vi testme.yml
---
- hosts: all

  tasks:
    - name: run this command and ignore the result
      shell: "grep -ci Hello /tmp/data.out"
      register: pingout
      ignore_errors: yes

    - debug: msg="{{ pingout.rc }}"

    - name: run the server if Hello is found in the above task
      command: echo "The server is UP since `uptime`"
      register: output1
      when:  pingout.rc == 0
    - debug: "{{ output1.stdout }}"

找到字符串后,我期望看到它执行并显示在输出中:自uptime起服务器已启动

但是,我在输出中看不到它。

ansible-playbook -i / tmp / myhost /root/testme.yml

输出:

PLAY [all] ******************************************************************************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************************************************
ok: [95.76.121.113]

TASK [run this command and ignore the result] *******************************************************************************************************************************
changed: [95.76.121.113]

TASK [debug] ****************************************************************************************************************************************************************
ok: [95.76.121.113] => {
    "msg": "0"
}

TASK [run the server if Hello is found in the above task] *******************************************************************************************************************
changed: [95.76.121.113]

TASK [debug] ****************************************************************************************************************************************************************
ok: [95.76.121.113] => {
    "msg": "Hello world!"
}

PLAY RECAP ******************************************************************************************************************************************************************
95.76.121.113               : ok=5    changed=2    unreachable=0    failed=0

2 个答案:

答案 0 :(得分:1)

您不需要检查rc。 Ansible知道命令失败的时间。

---
- hosts: localhost
  connection: local

  tasks:
    - name: First
      shell: "true"
      register: first
      ignore_errors: yes

    - name: Second
      shell: "true"
      register: second
      ignore_errors: yes
      when: first is not failed

    - name: Third
      shell: "true"
      register: third
      ignore_errors: yes
      when: second is not failed

答案 1 :(得分:0)

正确的语法是

- debug: msg="{{ output1.stdout }}"