如何用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 %}
修正要点说明
- 简化循环引用:直接用
config变量访问当前匹配块的配置,不用再通过索引openssh_match_config[k]调用,代码更简洁。 - 过滤冗余字段:内层循环跳过
matchkey和matchvalue,这两个值已经在Match行输出,无需重复打印。 - 适配OpenSSH键名格式:
- 普通键名用
title过滤器转成首字母大写格式(如chrootdirectory→ChrootDirectory)。 - 针对
x11forwarding这类特殊命名,先替换x11为X11再转大写,得到符合规范的X11Forwarding。
- 普通键名用
- 保证格式一致:每个配置项前保留3个空格,且每个
Match块之间添加空行,和目标配置的排版完全对齐。
内容的提问来源于stack exchange,提问作者johnny bravo
相关产品推荐
相关产品推荐

