Ansible正则不匹配时显示任务失败消息及stdout存储问题
问题分析与解决方案
核心问题
- 变量定义时机错误:
pass_max_days在vars块中定义,此时out还未被命令任务注册,初始解析时会因out不存在导致异常。 - 无匹配时抛出异常:当正则没有匹配项时,
select('match', regexp)|first会直接终止play,无法执行后续的失败提示任务。 - 错误的判断条件:
pass_max_days是提取出的字符串,没有rc属性,最后一个debug任务的when条件永远不会触发。
修正后的配置
- hosts: localhost vars: regexp: '(?i)^\s*PASS_MAX_DAYS\s+[0-9]+\s*$' tasks: - command: cat /tmp/login.defs register: out - set_fact: pass_max_days: "{{ out.stdout_lines | select('match', regexp) | first | split | last | default(None) }}" - debug: var: pass_max_days - debug: msg: Less than 90 days when: pass_max_days is not none and pass_max_days|int < 90 - debug: msg: Exactly 90 days when: pass_max_days is not none and pass_max_days|int == 90 - debug: msg: More than 90 days when: pass_max_days is not none and pass_max_days|int > 90 - debug: msg: Does not match! when: pass_max_days is none
关键修正点
- 将
pass_max_days的计算逻辑移到set_fact任务中,确保在out被注册后再执行解析。 - 添加
| default(None)处理无匹配的场景,避免first找不到元素时抛出异常。 - 所有数值判断的
when条件先检查pass_max_days is not none,防止空值转换整数时报错。 - 失败提示的条件改为
pass_max_days is none,直接判断是否匹配成功。
内容的提问来源于stack exchange,提问作者usertest5522
相关产品推荐
相关产品推荐

