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

如何在Ansible中用Jinja2过滤器格式化列表字符串为指定URL格式

Ansible:用Jinja2过滤器生成带HTTP前缀的地址列表

需要生成格式为"http://{ip_address}:{port}"的IP地址列表并写入JSON文件,当前已实现生成"{ip_address}:port"格式的代码:

vars:
  config:
    addresses: "{{ groups['other']
      | map('extract', hostvars)
      | map(attribute='ansible_host')
      | product([':' ~ other_port]) | map('join')
      }}" 

尝试过format过滤器但没找到正确用法,用Python列表推导式能实现但要求必须用Jinja2过滤器完成,想知道可行的实现方法。

可行的Jinja2过滤器实现方法

方法1:结合regex_replace与product/join

先给每个IP加上http://前缀,再和端口字符串拼接:

vars:
  config:
    addresses: "{{ groups['other']
      | map('extract', hostvars, 'ansible_host')
      | map('regex_replace', '^(.*)$', 'http://\\1')
      | product([':' ~ other_port])
      | map('join')
      }}"

通过regex_replace将原始IP替换为带http://的前缀格式,再和端口部分拼接成完整地址。

方法2:直接用format过滤器(更简洁)

其实format可以配合map直接生成目标格式,不需要product和join:

vars:
  config:
    addresses: "{{ groups['other']
      | map('extract', hostvars, 'ansible_host')
      | map('format', 'http://%s:' ~ other_port)
      }}"

这里把格式模板http://%s:{port}提前构造好(将other_port直接拼入模板),每个IP作为%s的填充值,一步生成完整地址。

方法3:一步完成正则替换拼接

把端口直接整合到regex_replace的替换字符串中,省去后续拼接步骤:

vars:
  config:
    addresses: "{{ groups['other']
      | map('extract', hostvars, 'ansible_host')
      | map('regex_replace', '^(.*)$', 'http://\\1:' ~ other_port)
      }}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:20:16