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

Ansible技巧:如何将community.general.filetree返回值统一转为列表

统一community.general.filetree返回值为列表的方法

可以通过Ansible的过滤器或条件判断,将单个字典格式的返回值包装成列表,确保无论目录内条目数量多少,返回值始终是列表类型。以下是两种实用方案:

方案1:使用ansible.utils.to_list过滤器

该过滤器专门用于将任意输入转为列表——若输入已是列表则保持原样,若为单个元素则自动包裹为列表。需确保环境已安装ansible.utils集合(通常随Ansible核心包默认安装,缺失可执行ansible-galaxy collection install ansible.utils补充)。

修改后的任务代码:

- name: Compose - Configs - Fetch files in config folder
  set_fact:
    compose_create_directories: >-
      {{ compose_create_directories + [{"project": item, "directories": lookup('community.general.filetree', compose_config_folder) | ansible.utils.to_list}] }}
  vars:
    compose_create_directories: []
  loop: "{{ compose_projects }}"

方案2:手动类型判断

若不想依赖额外集合,可直接在Jinja2表达式中做类型判断,将单个字典包装为列表:

修改后的任务代码:

- name: Compose - Configs - Fetch files in config folder
  set_fact:
    compose_create_directories: >-
      {{ compose_create_directories + [
          {"project": item, 
           "directories": lookup('community.general.filetree', compose_config_folder) 
                          if lookup('community.general.filetree', compose_config_folder) is list 
                          else [lookup('community.general.filetree', compose_config_folder)]
          }
        ] }}
  vars:
    compose_create_directories: []
  loop: "{{ compose_projects }}"

两种方案均可实现需求:当filetree返回单个字典时自动转为包含该字典的列表;当返回多个条目(列表形式)时,保持原结构不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:25:37