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

如何基于主机名字符串列表创建字典列表?Ansible数据转换求助

Ansible 字符串列表转HAProxy适配字典列表的简便实现

解决方案

直接通过regex_replace+from_json+list过滤器组合即可实现,无需额外依赖第三方集合:

vars:
  backends:
    - web1
    - web2
    - web3
  backends_dict: "{{ backends | map('regex_replace', '^(.*)$', '{\"name\": \"\\1\", \"address\": \"\\1:80\"}') | map('from_json') | list }}"

结果验证

添加debug任务查看转换后的数据:

tasks:
  - name: 输出转换结果
    debug:
      var: backends_dict

输出将完全匹配预期格式:

backends_dict:
  - address: web1:80
    name: web1
  - address: web2:80
    name: web2
  - address: web3:80
    name: web3

逻辑说明

  1. regex_replace:将每个主机名字符串替换为包含name和address字段的JSON格式字符串,\\1引用匹配到的完整主机名;
  2. from_json:把JSON格式的字符串转换为Ansible可识别的字典对象;
  3. list:将map过滤器返回的迭代器转为标准列表格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:44:54