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

如何用Ansible从JSON中获取一级键及对应直接子键列表?

解决Ansible循环生成独立配置文件的问题

假设你的food_sub_list事实结构如下:

food_sub_list:
  food_a:
    description: "Some description for food a"
    list_veg: ["carrot", "spinach"]
    some_bar: "value1"
  food_b:
    description: "Some description for food b"
    fruit_list: ["apple", "banana"]
    another_key: "value2"

核心思路

利用Ansible内置过滤器dict2items将顶层字典转换为可迭代的条目,再通过过滤排除description子键,最后循环生成每个food对应的配置文件。

方法一:模板内直接过滤

- name: Generate config files for each food
  copy:
    content: |
      # Config for {{ food_item.key }}
      {% for sub_key, sub_val in food_item.value.items() if sub_key != 'description' %}
      {{ sub_key }}: {{ sub_val | to_json }}
      {% endfor %}
    dest: "/etc/food_configs/{{ food_item.key }}.conf"
  loop: "{{ food_sub_list | dict2items }}"
  loop_control:
    loop_var: food_item

方法二:提前过滤子字典

如果需要复用过滤后的子字典,可以先通过过滤器移除description键:

- name: Generate formatted config files
  copy:
    content: "{{ filtered_sub_dict | to_nice_yaml }}"
    dest: "/etc/food_configs/{{ food_key }}.yaml"
  loop: "{{ food_sub_list | dict2items }}"
  vars:
    food_key: "{{ item.key }}"
    # 移除description子键并转回字典
    filtered_sub_dict: "{{ item.value | dict2items | rejectattr('key', 'equalto', 'description') | items2dict }}"

说明

  • dict2items:将顶层的food_sub_list字典转换为[{key: 'food_a', value: {...}}, ...]的列表结构,便于循环遍历。
  • rejectattr('key', 'equalto', 'description'):从子字典的条目列表中排除键为description的项,再通过items2dict转回字典格式。
  • to_nice_yaml/to_json:将过滤后的子字典格式化为可读性好的YAML/JSON内容写入配置文件,可根据需求调整格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:10:08