ansible中基于条件的执行

Condition based execution in ansible

我有一个场景,如果第一个条件成功则执行条件二,如果条件二成功则执行条件三。

下面是我试过的。

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

正确的语法是

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

,或

- debug: var=output1.stdout

您不需要勾选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