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

如何用Ansible Jinja2循环字典生成指定格式的OpenSSH Match配置

修正Jinja2代码生成符合要求的OpenSSH配置

原Ansible变量定义

vars:
  openssh_match_config: 
      test:
        matchkey: 'User'
        matchvalue: 'XXX'
        chrootdirectory: '/home/%u'
        maxsessions: '2'
      test2:
        matchkey: 'Address'
        matchvalue: '1.3.0.3.0/24,192.43.120.0/27'
        maxsessions: '3'
        x11forwarding: 'yes'
        otheropt: VAL1
        otheropt2: VAL2

目标OpenSSH配置格式

Match User XXX
   ChrootDirectory /home/%u
   MaxSessions 2
 
Match Address 1.3.0.3.0/24,192.43.120.0/27
   MaxSessions 3
   X11Forwarding yes
   otheropt  VAL1
   otheropt2 VAL2

现有问题代码

{% for k,v in openssh_match_config.items() %}
Match {{ openssh_match_config[k]['matchkey'] }} {{ openssh_match_config[k]['matchvalue'] }}
  {%for x in v.items() %}
   {{x}}
  {%endfor%}
{% endfor %}

修正后的Jinja2代码

{% for _, config in openssh_match_config.items() %}
Match {{ config.matchkey }} {{ config.matchvalue }}
  {% for key, value in config.items() if key not in ['matchkey', 'matchvalue'] %}
   {% set formatted_key = key | replace('x11', 'X11') | title %}
   {{ formatted_key }} {{ value }}
  {% endfor %}

{% endfor %}

修正要点说明

  1. 简化循环引用:直接用config变量访问当前匹配块的配置,不用再通过索引openssh_match_config[k]调用,代码更简洁。
  2. 过滤冗余字段:内层循环跳过matchkey和matchvalue,这两个值已经在Match行输出,无需重复打印。
  3. 适配OpenSSH键名格式:
    • 普通键名用title过滤器转成首字母大写格式(如chrootdirectory→ChrootDirectory)。
    • 针对x11forwarding这类特殊命名,先替换x11为X11再转大写,得到符合规范的X11Forwarding。
  4. 保证格式一致:每个配置项前保留3个空格,且每个Match块之间添加空行,和目标配置的排版完全对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:01:33