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

如何将嵌套列表内的字典列表转换为Ansible可用的额外变量?

嘿,我刚好处理过类似的Ansible数据转换需求,给你两个针对性的解决方案,看哪种更贴合你的with_nested结构:

解决方案1:用Ansible过滤器快速转换(适用于单层字典列表)

如果你的with_nested是直接包含目标字典的单层列表(比如每个元素都有name和action字段,像[{"name": "dom_difference_results", "action": "create"}, ...]),可以用dict_kv过滤器一步到位:

- name: Generate solr_cores from single-level list
  set_fact:
    solr_cores: "{{ with_nested | map('community.general.dict_kv', 'name', 'action') | list }}"

解释:dict_kv过滤器会把每个字典里的name字段值作为键,action字段值作为值,生成你需要的单个键值对字典。最后用list把map对象转成列表,就完美得到了你想要的solr_cores格式。

解决方案2:Jinja2循环处理嵌套结构(适用于多层嵌套的with_nested)

如果你的with_nested是多层嵌套的列表(比如是列表套列表的结构,像[[{...}, {...}], [{...}]]),可以用Jinja2的循环和列表操作来手动构建:

- name: Generate solr_cores from nested list
  set_fact:
    solr_cores: |
      {% set result_list = [] %}
      {% for outer_list in with_nested %}
        {% for core_dict in outer_list %}
          {% do result_list.append({core_dict.name: core_dict.action}) %}
        {% endfor %}
      {% endfor %}
      {{ result_list }}

解释:我们先初始化一个空列表result_list,然后逐层遍历with_nested的嵌套结构,把每个子字典转换成单个键值对的新字典,逐个添加到结果列表里。最后把这个列表赋值给solr_cores,就能得到目标格式。

在uri模块中使用生成的solr_cores

得到solr_cores之后,直接在uri模块里用to_json过滤器转成JSON格式即可发送请求:

- name: Send request to Solr API
  uri:
    url: "http://your-solr-instance:8983/admin/cores"
    method: POST
    body: "{{ solr_cores | to_json }}"
    headers:
      Content-Type: application/json
    status_code: 200

内容的提问来源于stack exchange,提问作者Peter Scott Hayman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:42:59