Ansible failure message based on conditional failed_when

Viewed 2875

I'm trying to clean up some of our expected errors and make them more understandable to the operators running the playbooks. The code below works just fine, but I would like to assign a custom message to each of the failure conditions. For example, if var1 does not equal 4 then I'd like to present a message that says "There were not 4 entries in the lldp neighbor for neighbor x"

   - name: Verify Number of bundles for output of show lldp neigh
     set_fact:
       var1: "{{lldp_spine3.data | regex_findall('ae1')}}"
       var2: "{{lldp_spine3.data | regex_findall('ae2')}}"
     failed_when: (var1 != 4) or (var2 | length != 4)
 

I know I can split those up and follow the logic below but I'd like to know if I can accomplish this in a single play.

- fail:
    msg: "There were not 4 entries in the lldp neighbor for neighbor x"
  when: var1|length != 4
  
- fail:
    msg: "There were not 4 entries in the lldp neighbor for neighbor y"
  when: var2|length != 4
2 Answers

There is assert module for that:

- assert:
    that: var2|length == 4
    msg: 'lldp should have four neighbors'

Few more tricks:

  1. Some assertion can be run against localhost and only once (f.e. ansible version), there is run_once: true for that.

  2. Add tags: [always] to guarantee that assertion task is executed.

What about using a loop?

Given the playbook:

- hosts: all
  gather_facts: no

  vars:
    var1: abcde
    var2: abcd
      
  tasks:
    - fail:
        msg: "{{ item.msg }}"
      when: item.condition
      loop_control:
        label: "{{ item.item }} is {{ 'invalid' if item.condition else 'valid' }}"
      loop: 
        - msg: There were not 4 entries in the lldp neighbor for neighbor var1
          condition: "{{ var1 | length != 4 }}"
          item: var1
        - msg: There were not 4 entries in the lldp neighbor for neighbor var2
          condition: "{{ var2 | length != 4 }}"
          item: var2

This yields the recap:

PLAY [all] **********************************************************************************************************

TASK [fail] *********************************************************************************************************
failed: [localhost] (item=var1 is invalid) => {"ansible_loop_var": "item", "changed": false, "item": {"condition": true, "item": "var1", "msg": "There were not 4 entries in the lldp neighbor for neighbor var1"}, "msg": "There were not 4 entries in the lldp neighbor for neighbor var1"}
skipping: [localhost] => (item=var2 is valid) 

PLAY RECAP **********************************************************************************************************
localhost                  : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   
Related