The when clause

The when clause is useful when you need to check the output from the result and act accordingly. Let's look at a simple example of its usage in chapter5_1.yml:

    ---
- name: IOS Command Output
hosts: "iosv-devices"
gather_facts: false
connection: local
vars:
cli:
host: "{{ ansible_host }}"
username: "{{ username }}"
password: "{{ password }}"
transport: cli
tasks:
- name: show hostname
ios_command:
commands:
- show run | i hostname
provider: "{{ cli }}"
register: output
- name: show output
when: '"iosv-2" in "{{ output.stdout }}"'
debug:
msg: '{{ output }}'

We have seen all the elements in this playbook before in Chapter 4, Python Automation Framework – Ansible Basics; the only difference is on the second task, as we are using the when clause to check if the output contains iosv-2. If true, we will proceed to the task, which is using the debug module to display the output. When the playbook is run, we will see the following output:

    <skip>
TASK [show output]
*************************************************************
skipping: [ios-r1]
ok: [ios-r2] => {
"msg": {
"changed": false,
"stdout": [
"hostname iosv-2"
],
"stdout_lines": [
[
"hostname iosv-2"
]
],
"warnings": []
}
}
<skip>

We can see that the iosv-r1 device is skipped from the output because the clause did not pass. We can further expand this example in chapter5_2.yml to only apply configuration changes when the condition is met:

    <skip> 
tasks:
- name: show hostname
ios_command:
commands:
- show run | i hostname
provider: "{{ cli }}"
register: output
- name: config example
when: '"iosv-2" in "{{ output.stdout }}"'
ios_config:
lines:
- logging buffered 30000
provider: "{{ cli }}"

We can see the execution output here:

    TASK [config example]   
**********************************************************
skipping: [ios-r1]
changed: [ios-r2]

PLAY RECAP
***********************************************************
ios-r1 : ok=1 changed=0 unreachable=0 failed=0
ios-r2 : ok=2 changed=1 unreachable=0 failed=0

Note that the output is showing that only ios-r2 is changed while ios-r1 is skipped. The when clause is also very useful in situations such as when the setup module is supported and you want to act on some facts that were gathered initially. For example, the following statement will ensure only the Ubuntu host with major release 16 will be acted upon by placing a conditional statement in the clause:

when: ansible_os_family == "Debian" and ansible_lsb.major_release|int >= 16
For more conditionals, check out the Ansible conditionals documentation (http://docs.ansible.com/ansible/playbooks_conditionals.html).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.34.197