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

Ansible中序列化/反序列化及遍历对象失败的问题求助

问题原因

你的错误出在反序列化后的数据结构处理上:

  • 存储的字符串最外层是spaces:键,经过from_yaml反序列化后,得到的是一个顶级字典:{'spaces': {'admins': {...}, 'team1': {...}, ...}}
  • 你直接把这个顶级字典传给ansible.builtin.dict lookup插件,插件会把顶级的spaces键当作唯一的字典项返回(单元素字典),而loop要求接收列表类型,因此抛出异常。
修复方案

只需要在反序列化后,取spaces对应的值(即包含admins、team1等的内层字典)传给dict lookup即可:

- name: 遍历空间信息
  ansible.builtin.debug:
    msg: "Space {{ item.key }} is {{ item.value.description }} ({{ item.value.color }})"
  loop: "{{ lookup('ansible.builtin.dict', dynamic_data.elastic_setup_userenv.spaces_yaml | ansible.builtin.from_yaml).spaces }}"

或者更清晰的分步写法:

- name: 反序列化spaces YAML字符串
  ansible.builtin.set_fact:
    parsed_spaces: "{{ dynamic_data.elastic_setup_userenv.spaces_yaml | ansible.builtin.from_yaml }}"

- name: 遍历空间信息
  ansible.builtin.debug:
    msg: "Space {{ item.key }} is {{ item.value.description }} ({{ item.value.color }})"
  loop: "{{ lookup('ansible.builtin.dict', parsed_spaces.spaces) }}"
逻辑验证

反序列化后的parsed_spaces数据结构为:

{
  "spaces": {
    "admins": {"description": "...", "color": "...", "initials": "..."},
    "team1": {"description": "...", "color": "...", "initials": "..."},
    "team2": {"description": "...", "color": "...", "initials": "..."},
    "team3": {"description": "...", "color": "...", "initials": "..."},
    "team4": {"description": "...", "color": "...", "initials": "..."}
  }
}

取parsed_spaces.spaces得到内层字典,传给dict lookup后会生成包含各空间项的列表,完全符合loop的输入要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 17:12:55