How do I exit Ansible play without error on a condition

前端 未结 6 1650
我在风中等你
我在风中等你 2021-01-31 02:02

I want to exit without an error (I know about assert and fail modules) when I meet a certain condition. The following code exits but with a failure:

  tasks:

           


        
6条回答
  •  粉色の甜心
    2021-01-31 02:48

    Lets use what Tymoteusz suggested for roles:

    Split your play into two roles where first role will execute the check (and sets some variable holding check's result) and second one will act based on result of the check.

    I have created aaa.yaml with this content:

    ---
    - hosts: all
      remote_user: root
      roles:
        - check
        - { role: doit, when: "check.stdout == '0'" }
    ...
    

    then role check in roles/check/tasks/main.yaml:

    ---
    - name: "Check if we should continue"
      shell:
        echo $(( $RANDOM % 2 ))
      register: check
    - debug:
        var: check.stdout
    ...
    

    and then role doit in roles/doit/tasks/main.yaml:

    ---
    - name: "Do it only on systems where check returned 0"
      command:
        date
    ...
    

    And this was the output:

    TASK [check : Check if we should continue] *************************************
    Thursday 06 October 2016  21:49:49 +0200 (0:00:09.800)       0:00:09.832 ****** 
    changed: [capsule.example.com]
    changed: [monitoring.example.com]
    changed: [satellite.example.com]
    changed: [docker.example.com]
    
    TASK [check : debug] ***********************************************************
    Thursday 06 October 2016  21:49:55 +0200 (0:00:05.171)       0:00:15.004 ****** 
    ok: [monitoring.example.com] => {
        "check.stdout": "0"
    }
    ok: [satellite.example.com] => {
        "check.stdout": "1"
    }
    ok: [capsule.example.com] => {
        "check.stdout": "0"
    }
    ok: [docker.example.com] => {
        "check.stdout": "0"
    }
    
    TASK [doit : Do it only on systems where check returned 0] *********************
    Thursday 06 October 2016  21:49:55 +0200 (0:00:00.072)       0:00:15.076 ****** 
    skipping: [satellite.example.com]
    changed: [capsule.example.com]
    changed: [docker.example.com]
    changed: [monitoring.example.com]
    

    It is not perfect: looks like you will keep seeing skipping status for all tasks for skipped systems, but might do the trick.

提交回复
热议问题