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

Ansible字典列表遍历问题求助:无法遍历组变量

问题分析与解决

1. 修正组变量的结构问题

你的group_vars/myvar变量存在缩进错误,导致information并未成为file1/file2的子属性,而是和它们同级的列表元素,同时information下的字段无需写成列表格式(它们是单个键值对,而非多条目)。正确的变量结构如下:

filedata:
  - file1:
      information:
        path: "/tmp"
        filename: "*.log"
        retention: "+30"
  - file2:
      information:
        path: "/var/log"
        filename: "*.lg"
        retention: "+10"

2. 修正Playbook的语法错误

你的Playbook存在两处语法错误:

  • host 需改为 hosts
  • task 需改为 tasks

3. 正确遍历变量的Playbook写法

filedata是一个列表,每个元素是仅包含单个键(file1/file2)的字典。我们可以通过map('dict2items')将每个字典转换为键值对,再用flatten展开嵌套列表,从而直接遍历获取目标字段:

---
- name: loop test
  hosts: myvar
  gather_facts: false
  tasks:
    - name: loop through filedata
      debug:
        msg: "fileid={{ item.key }}, path={{ item.value.information.path }}, filename={{ item.value.information.filename }}, retention={{ item.value.information.retention }}"
      loop: "{{ filedata | map('dict2items') | flatten }}"

逻辑说明:

  • map('dict2items'):将列表中每个单键字典(如{"file1": {...}})转换为键值对结构
  • flatten:把嵌套的列表展开为单层,方便直接遍历提取字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:35:23