Search code examples
ansibleassert

How to use assert module in Ansible?


I want an Ansible code that asserts and checks these two interfaces are not equal:

bond_interfaces: [eno5, eno6]
node0125.computer.me: 
          management_ip: x.x.x.x
          management_interface: ens3f0
          bond_interfaces: [eno5, eno6]
          private_ip: x.x.x.x
          # ilo_ip: x.x.x.x
          ansible_host: '{{ management_ip }}'
          tier: balanced
          os_version: 20.04

Solution

  • According the documentation of assert module – Asserts given expressions are true a minimal example playbook could look like

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      vars:
    
        node0125_compute_neda: 
          bond_interfaces: [eno5, eno6]
    
      tasks:
    
      - assert:
          that:
            - node0125_compute_neda.bond_interfaces[0] != node0125_compute_neda.bond_interfaces[1]
          fail_msg: "Network bond is not over two different interfaces"
    

    resulting into an output of

    TASK [assert] ******************
    ok: [localhost] => changed=false
      msg: All assertions passed
    

    or if on the same interface

    TASK [assert] ******************************************************************************************************************************************
    fatal: [localhost]: FAILED! => changed=false
      assertion: node0125_compute_neda.bond_interfaces[0] != node0125_compute_neda.bond_interfaces[1]
      evaluated_to: false
      msg: Network bond is not over two different interfaces
    

    Since bond_interfaces: [eno5, eno6] is a list with two elements, the check will assure that the first list element is not equal the second list element.

    If the list will have only two elements, it would also be possible to compare the first with the last element.

      - assert:
          that:
            - node0125_compute_neda.bond_interfaces | length == 2
            - node0125_compute_neda.bond_interfaces | first != node0125_compute_neda.bond_interfaces | last
          fail_msg: "Network bond is not over two different interfaces"