首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >包括来自多个文件夹的变量,同时将文件夹名称前缀到变量名称

包括来自多个文件夹的变量,同时将文件夹名称前缀到变量名称
EN

Stack Overflow用户
提问于 2021-10-06 15:24:41
回答 2查看 45关注 0票数 1

我尝试从具有以下结构的文件夹中递归导入变量:

代码语言:javascript
复制
containers
|_ deluge
  |_ defaults
    |_ main.yml
  |_ tasks
    |_ main.yml
|_ jellyfin
  |_ defaults
    |_ main.yml
  |_ tasks
    |_ main.yml

每个文件夹都有一个default/main.yml文件,如下所示:

代码语言:javascript
复制
---
container_name: deluge

port: 8112
homer_url: "http://{{ ansible_host }}:{{ port }}"

这些变量在所有文件夹中具有相同的名称。

我想以下面的形式将homer_url变量导入到行动手册中,这样我就可以通过使用homer_containers.delugehomer_containers.jellyfin等来处理它们:

代码语言:javascript
复制
homer_containers {
   deluge: "http://myhost.com:8112"
   plex: "http://myhost.com:32400"
   jellyfin: "http://myhost.com:8096"
}

下面是我尝试这样做的方法:

代码语言:javascript
复制
---
- name: Get a list of containers
  delegate_to: localhost
  become: no
  find:
    paths: 
      - "roles/containers"
    file_type: directory
    excludes: "homer"
    recurse: no
  register: containers

- name: Include all .json and .jsn files in vars/all and all nested directories (2.3)
  include_vars:
    dir: "{{ playbook_dir }}/{{ item.path }}/defaults"
    files_matching: main.yml
    name: "{{ item.path.split('/')[-1] }}"
  with_items: "{{ containers.files }}"
  no_log: true

- name: print out
  debug:
    var: deconz.homer_url

- name: Populate the dictionary
  set_fact:
    homer_containers: "{{ homer_containers | default({}) | combine ( { item.path.split('/')[-1] : vars[item.path.split('/')[-1] + '.homer_url'] } ) }}"
    cacheable: true
  with_items: "{{ containers.files }}"

- name: print out
  debug:
    var: homer_containers

但是,Ansible无法将变量名解析为实际的变量:

代码语言:javascript
复制
TASK [containers/homer : print out] 
ok: [myhost] => {
    "deconz.homer_url": "http://myhost.com:8085"
}

TASK [containers/homer : Populate the dictionary]
fatal: [myhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. 
The error was: 'dict object' has no attribute 'deconz.homer_url'}
EN

回答 2

Stack Overflow用户

发布于 2021-10-07 03:39:22

它应该是foo['bar']['baz'],而不是像foo['bar.baz']那样访问变量。

所以简单的改变:

代码语言:javascript
复制
vars[item.path.split('/')[-1] + '.homer_url']

代码语言:javascript
复制
vars[item.path.split('/')[-1]]['homer_url']
票数 0
EN

Stack Overflow用户

发布于 2021-10-07 11:32:48

@Rickkwa的答案在略微调整后有效。我还更改了结构,以包含另一个变量(homer_category)

代码语言:javascript
复制
- name: Populate the dictionary
  set_fact:
    homer_urls: "{{ homer_urls | default([]) + [{ 'name': item.path.split('/')[-1], 'url' : lookup('vars', item.path.split('/')[-1])['homer_url'] | default(''), 'category': lookup('vars', item.path.split('/')[-1])['homer_category'] | default ('') }] }}"
  with_items: "{{ containers.files }}"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69468485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档