使用Ansible检测网络设备双端口状态并实现多场景消息输出的技术咨询
嘿,我来帮你搞定这个Ansible的问题!先分两部分解答你的疑问:
一、正则未匹配时set_fact的取值
当regex_search没有找到匹配的字符串时,它会返回None(在Ansible的Jinja2语境里就是空值)。所以你的set_fact中定义的id变量会被设置为None。后续你可以通过{{ PORT37.id is none }}来判断是否匹配失败,或者用{{ PORT37.id | default('') }}给它一个默认空字符串来避免报错。
不过其实有更简洁的方式来判断端口状态——直接用Ansible的search测试器,不用手动处理regex_search的返回值,后面我会讲到。
二、处理四种端口状态组合的思路
首先,我们应该先明确两个端口各自的Up/Down状态,再根据组合输出对应消息。推荐用布尔变量来存储每个端口是否Up,这样条件判断会非常清晰。
调整你的代码如下:
- name: CHECKING PORT 37,38 raw: diag switch-controller switch-info lldp neighbors-summary register: PORT # 用search测试器直接判断端口是否Up,结果存为布尔值 - set_fact: port37_up: "{{ PORT.stdout is search('port37.*Up') }}" - set_fact: port38_up: "{{ PORT.stdout is search('port38.*Up') }}" # 根据四种组合输出对应提示 - debug: msg: "Msg: Two ports are up" when: port37_up and port38_up - debug: msg: "Msg: Port 38 is up but port 37 is down" when: not port37_up and port38_up - debug: msg: "Msg: Port 37 is up but port 38 is down" when: port37_up and not port38_up - debug: msg: "Msg: Two ports are down" when: not port37_up and not port38_up
如果你想更简洁,也可以用一个debug模块配合Jinja2的条件表达式一次性生成消息:
- debug: msg: >- {% if port37_up and port38_up %}Msg: Two ports are up {% elif not port37_up and port38_up %}Msg: Port 38 is up but port 37 is down {% elif port37_up and not port38_up %}Msg: Port 37 is up but port 38 is down {% else %}Msg: Two ports are down{% endif %}
这样不管哪种状态组合,都会输出对应的提示信息啦。
内容的提问来源于stack exchange,提问作者SPR
相关产品推荐
相关产品推荐

