我正在尝试清理一些预期的错误,并使运行这些手册的操作员更容易理解。下面的代码工作正常,但是我想为每个失败条件分配一个自定义消息。例如,如果var1不等于4,那么我想显示一条消息,说“ lldp邻居中x邻居中没有4个条目”
- 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)
我知道我可以将它们分解并遵循下面的逻辑,但是我想知道我是否可以在单个游戏中完成此任务。
- 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
答案 0 :(得分:0)
有assert
个模块用于
- assert:
that: var2|length == 4
msg: 'lldp should have four neighbors'
更多技巧:
某些声明可以针对localhost运行,并且只能运行一次(例如ansible版本),为此run_once: true
。
添加tags: [always]
以确保执行断言任务。
答案 1 :(得分:0)
使用loop
怎么样?
给出剧本:
- 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
这产生了回顾:
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