ansible

Ansible - How to skip registering a variable if the when condition is not met


-  shell: "echo 'hi'"
   register: output
-  shell: "ps -ef"
   register: output
   when: output.stdout =="hello"
 - debug: var=output

The final output variable is defined as below:

TASK [Display output] **********************************************************

    ok: [localhost] => 
{
    "output": 
   {
        "changed": false,
        "skip_reason": "Conditional check failed",
        "skipped": true
    }
}

Even though the task 2 is skipped, the variable gets registered. How can I skip the register if the condition is not met?


Solution

  • Register both outcomes as output1 and output2. Use 'set_fact' to set a new variable 'output' according to your condition.

    - shell: "echo 'hi'"
      register: output1
    - shell: "ps -ef"
      register: output2
    - set_fact:
        output: "{{ output2 if output2.stdout =='hello' | default(output1)}}"
    - debug: var=output