You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible中用字典多正则匹配字段遇模板无效问题求助

解决Ansible批量正则匹配结果生成的模板错误问题

需求说明

将字典中定义的多个正则表达式应用到指定字符串字段,返回每个正则的匹配状态(匹配返回true,不匹配返回false)。

正则配置字典

myconfig:
  kindA:
    regexp: "^exampleA.+$"
  kindB:
    regexp: "^exampleB.+$"
  kindC:
    regexp: "^exampleC.+$"

期望输出结果

{
  "kindA": false,
  "kindB": true, # description field matched !
  "kindC": false
}

问题代码

尝试的Playbook代码因模板语法错误无法通过检测:

- ansible.builtin.set_fact:
   regex_result: "{{ regex_result | default({}) |
     combine({ item.key: (my_current_obj.description
       | regex_search(item.value.regexp)
       | bool) }
     }}"
 loop: "{{ lookup('dict', myconfig) }}"

修正方案

问题源于括号不匹配和多行模板解析错误,以下是两种可行的修正版本:

版本1:单行紧凑写法

- ansible.builtin.set_fact:
    regex_result: "{{ regex_result | default({}) | combine({ item.key: (my_current_obj.description | regex_search(item.value.regexp) | bool) }) }}"
  loop: "{{ lookup('dict', myconfig) }}"

版本2:多行可读写法

使用YAML的折叠标量>-处理多行模板,避免解析错误:

- ansible.builtin.set_fact:
    regex_result: >-
      {{ regex_result | default({}) 
         | combine({ item.key: (my_current_obj.description 
                               | regex_search(item.value.regexp) 
                               | bool) }) }}
  loop: "{{ lookup('dict', myconfig) }}"

错误原因解析

  1. 括号缺失:原代码中combine函数的参数括号未完全闭合,导致Jinja2模板语法无效。
  2. 多行解析问题:直接换行的模板内容会被YAML拆分为多个片段,Ansible无法识别完整的Jinja2表达式,使用>-可将多行内容合并为单行解析,同时保留代码可读性。

内容的提问来源于stack exchange,提问作者LostReality

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 05:17:43