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

如何将Ansible列表转换为字典列表并为每个项添加相同键值对

问题描述

我有一组AWS实例ID,存储在instance_running.instance_ids变量中,内容如下:

ok: [localhost] => {
    "instance_running.instance_ids": [
        "i-05a765076f4cbf03b",
        "i-096b8a656d875f38a",
        "i-0b5156565ac17c9e4",
        "i-0865656657565edd5"
    ]
}

我需要将其转换为符合以下格式的targets变量,所有实例ID对应的端口都使用同一个host_port变量:

targets:
  - Id: "{{ instance_id }}"
    Port: "{{ host_port }}"

我搞不懂怎么用map函数和community.general.dict实现这个需求,求解决方案。


解决方案

方法1:用map + community.general.dict快速生成

这是最简洁的方式,利用map遍历实例ID列表,每个ID都通过community.general.dict生成指定结构的字典,最后转成列表:

targets: "{{ instance_running.instance_ids | map('community.general.dict', Id='', Port=host_port) | list }}"

原理:community.general.dict会根据你传入的键值对生成字典,这里固定Port为host_port的值,Id留空后,map会自动把遍历到的每个实例ID填充到Id字段里,最终得到你需要的targets列表结构。

方法2:用循环构建(更直观)

如果对map函数不太熟悉,可以用set_fact配合循环逐个添加目标项:

- name: 构建targets列表
  set_fact:
    targets: "{{ targets | default([]) + [{'Id': item, 'Port': host_port}] }}"
  loop: "{{ instance_running.instance_ids }}"

每次循环都会把当前实例ID和host_port组成的字典,追加到targets列表中(默认初始为空列表)。

方法3:用map + 字符串转JSON(兼容旧版Ansible)

如果你的Ansible版本不支持community.general.dict,可以用字符串替换的方式生成JSON结构,再转成字典:

targets: "{{ instance_running.instance_ids | map('regex_replace', '^(.*)$', '{\"Id\": \"\\1\", \"Port\": \"' ~ host_port ~ '\"}') | map('from_json') | list }}"

这里先用regex_replace把每个实例ID替换成符合格式的JSON字符串,再通过from_json转成字典,最后合并成列表。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:32:16