Introduction
Someone recently asked a question on x/twitter, on how to perform conditional statements in ansible.

I thought I quickly help out, and share it with everyone in the community 🙂

“IF” statements on Ansible

Ansible is not natively capable of conditional statements like GPLs(General Purpose Languages). Instead, it utilises a combination of dynamic variable assignment (with modules like set_fact) and conditional execution (with the when clause)

This all comes down to modules use. In a scenario like this, you would use a read module to extract data and register it, then facts module to set the conditional statement (if statement) by dynamically assign it variable and write module to perform the action based on condition.

Example Playbook with conditional

Modules:
1.ios_command
2.set_fact
3.ios_config

In this example, I will set the ip address of an interface based on a conditional statement: current ip address. IF a specific interface has an assigned ip address of 192.168.1.1/24 then I will change it 192.168.1.2/24.

1.

  • name: Change interface IP based on current IP address hosts: switches gather_facts: no tasks:
    • name: Get the IP address of the specific interface by directly filtering, using a read module ios_command: commands:
      • show ip interface brief | include GigabitEthernet0/1
        register: interface_ip_output

2.
– name: Check if interface GigabitEthernet0/1 has IP 192.168.1.1 by using a conditional/variable module and parse output into interface_has_ip variable
set_fact:
interface_has_ip: “{{ ‘192.168.1.1’ in interface_ip_output.stdout }}”

3.
– name: Change interface IP when the variable of interface_has_ip is true
ios_config:
lines:
– ip address 192.168.1.2 255.255.255.0
parents: interface GigabitEthernet0/1
when: interface_has_ip

Quick Summary

  1. ios_command module: Will retrieve the IP address of the specific interface by directly filtering using cli include. This will be our “read module”
  2. Set_facts module: This checks if interface GigabitEthernet0/1 has IP 192.168.1.1 by using a conditional/variable module and parse output into interface_has_ip variable. In hindsight all what it’s doing is dynamically assigning the output into a variable during execution. This will be used as a “conditional module”
  3. ios_config module: This will change the interface IP to 192.168.1.2 when the dynamic variable of interface_has_ip is true. This is our write module.

Hope you all found that helpful, until next time bye 🙋‍♂️ for now.

Leave a comment

Trending