Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible failure message based on conditional failed_when

Tags:

ansible

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
like image 790
neteng225 Avatar asked Feb 04 '26 21:02

neteng225


1 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.

like image 141
George Shuklin Avatar answered Feb 08 '26 23:02

George Shuklin