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

Ansible导入多目录同名变量并前缀目录名生成字典报错如何解决

报错原因

你遇到的报错核心是变量访问逻辑错误:
当你通过include_vars指定name参数为容器名(比如deluge、deconz)后,Ansible会生成顶层字典变量,结构为:

deconz:
  homer_url: "http://myhost.com:8085"
  # 其他从main.yml导入的变量

你之前的debug任务能正常输出deconz.homer_url,是因为debug模块的var参数支持自动解析点语法的嵌套变量;但你在set_fact中写的vars[item.path.split('/')[-1] + '.homer_url']是尝试从全局vars字典里查找名为deconz.homer_url的顶层变量,这个变量不存在,因此触发报错。

修复方法

把Populate the dictionary任务的变量访问逻辑改成嵌套字典访问即可,修改后的代码如下:

- name: Populate the dictionary
  set_fact:
    homer_containers: "{{ homer_containers | default({}) | combine( { container_name : vars[container_name]['homer_url'] } ) }}"
    cacheable: true
  vars:
    # 提前提取容器名,避免重复写split逻辑
    container_name: "{{ item.path.split('/')[-1] }}"
  with_items: "{{ containers.files }}"
可选优化

你可以把重复的容器名提取逻辑统一,提升代码可读性:

---
- name: Get a list of containers
  delegate_to: localhost
  become: no
  find:
    paths: 
      - "roles/containers"
    file_type: directory
    excludes: "homer"
    recurse: no
  register: containers_raw

# 预处理容器列表,提前提取容器名
- name: Process container list
  set_fact:
    containers: "{{ containers | default([]) + [{'path': item.path, 'name': item.path.split('/')[-1]}] }}"
  with_items: "{{ containers_raw.files }}"

- name: Load container default vars
  include_vars:
    dir: "{{ playbook_dir }}/{{ item.path }}/defaults"
    files_matching: main.yml
    name: "{{ item.name }}"
  with_items: "{{ containers }}"
  no_log: true

- name: Build homer_containers dict
  set_fact:
    homer_containers: "{{ homer_containers | default({}) | combine( { item.name : vars[item.name]['homer_url'] } ) }}"
    cacheable: true
  with_items: "{{ containers }}"

- name: Print homer_containers
  debug:
    var: homer_containers

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:39:01