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

Ansible Jinja模板遍历子变量异常:生成项目专属rsyslog配置文件

解决Jinja模板遍历子变量生成多项目rsyslog配置文件的问题

问题说明

遍历rsyslog_custom_templates变量时,原模板使用item.1的循环逻辑无法正常工作,需要为每个项目生成专属的rsyslog配置文件,每个文件对应项目自身的日志模板规则。

当前配置与模板

group_vars配置

rsyslog_custom_templates:
 name: 
   projet1:
     - template_tag: "log1"
       template_dir: "/dir1"
     - template_tag: "log2"
       template_dir: "/dir2"
   projet2:
     - template_tag: "log1"
       template_dir: "/dir1"

原Jinja模板(无法正常工作)

{% for item in rsyslog_custom_templates.name %}
$template "{{ item.1.template_tag }}","{{ item.1.template_dir }}"
if $syslogtag == "{{ item.1.template_tag }}" then -?"{{ item.1.template_tag }}"
{% endfor %}

修正方案

1. 调整Jinja模板逻辑

原模板错误在于直接遍历字典对象,未正确解析键值对结构。修改后的模板专注于遍历单个项目的模板列表:

{% for template in templates %}
$template {{ template.template_tag }},{{ template.template_dir }}
if $syslogtag == {{ template.template_tag }} then -?{{ template.template_tag }}
{% endfor %}

2. 配置Ansible任务生成多文件

通过dict2items将字典转换为可遍历的键值对列表,为每个项目单独生成配置文件:

- name: 生成各项目rsyslog配置文件
  template:
    src: rsyslog_custom.j2
    dest: "/etc/rsyslog.d/{{ item.key }}.conf"
  loop: "{{ rsyslog_custom_templates.name | dict2items }}"
  vars:
    templates: "{{ item.value }}"

验证结果

执行任务后,会生成符合预期的配置文件:

  • projet1.conf
$template log1,/dir1
if $syslogtag == log1 then -?log1
$template log2,/dir2
if $syslogtag == log2 then -?log2
  • projet2.conf
$template log1,/dir1
if $syslogtag == log1 then -?log1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:25:27