我尝试从具有以下结构的文件夹中递归导入变量:
containers
|_ deluge
|_ defaults
|_ main.yml
|_ tasks
|_ main.yml
|_ jellyfin
|_ defaults
|_ main.yml
|_ tasks
|_ main.yml每个文件夹都有一个default/main.yml文件,如下所示:
---
container_name: deluge
port: 8112
homer_url: "http://{{ ansible_host }}:{{ port }}"这些变量在所有文件夹中具有相同的名称。
我想以下面的形式将homer_url变量导入到行动手册中,这样我就可以通过使用homer_containers.deluge、homer_containers.jellyfin等来处理它们:
homer_containers {
deluge: "http://myhost.com:8112"
plex: "http://myhost.com:32400"
jellyfin: "http://myhost.com:8096"
}下面是我尝试这样做的方法:
---
- 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无法将变量名解析为实际的变量:
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'}发布于 2021-10-07 03:39:22
它应该是foo['bar']['baz'],而不是像foo['bar.baz']那样访问变量。
所以简单的改变:
vars[item.path.split('/')[-1] + '.homer_url']至
vars[item.path.split('/')[-1]]['homer_url']发布于 2021-10-07 11:32:48
@Rickkwa的答案在略微调整后有效。我还更改了结构,以包含另一个变量(homer_category)
- 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 }}"https://stackoverflow.com/questions/69468485
复制相似问题