The when clause

The when clause is useful when you need to check the output of a variable or a play execution result and act accordingly. We saw a quick example of the when clause in Chapter 4, The Python Automation Framework – Ansible Basics, when we looked at the Ansible 2.5 best practices structure. If you recall, the task only ran when the network operating system of the device was the Cisco IOS. Let's look at another example of its use 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: ...

Get Mastering Python Networking - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.