在Ansible中,在一个角色中,我有这样的vars文件:
vars/
app1.yml
app2.yml每个文件包含特定于应用程序/网站的vars,如下所示:
name: app1
git_repo: https://github.com/philgyford/app1.git
# ...理想情况下,在不事先知道哪些应用程序有可变文件的情况下,我想得到一个名为apps的数组,如下所示:
apps:
- name: app1
git_repo: https://github.com/philgyford/app1.git
# ...
- name: app2
git_repo: https://github.com/philgyford/app2.git
# ...它将文件中的变量组合为一个。
我知道我可以像这样加载所有的变量文件:
- name: Load var files
with_fileglob:
- ../vars/*.yml
include_vars: '{{ item }}'但是,如果每个文件都有相同的变量名,它将覆盖以前的每一组变量。我看不到加载变量并将它们放入apps数组的方法。
如果这是让这样的事情成为可能的唯一方法的话,我愿意稍微重新安排一些事情。
发布于 2019-01-03 02:33:59
好吧,您不能直接构建数组,但是您可以通过dict实现同样的工作。
假设您想要构造一个数组:
[{
name: 'bob',
age: 30
}, {
name: 'alice',
age: 35
}]您可以将每个元素放入一个文件中,例如:
bob.yml
bob:
name: bob
age: 30alice.yml
alice:
name: alice
age: 35将这些文件放在同一个dir (例如user)中,然后使用include_vars加载整个dir:
- name: Include vars
include_vars:
name: users
dir: user这将给您一个dict users:
users:
alice:
name: alice
age: 35
bob:
name: bob
age: 30使用ansible中的dict2items过滤器,您将得到想要的数组
发布于 2020-08-05 15:33:54
使用属性名字并将包含的变量放入字典中。使词典的名称符合你的需要。例如
- name: Load var files
include_vars:
file: "{{ item }}"
name: "incl_vars_{{ item|basename|splitext|first }}"
with_fileglob:
- vars/*.yml然后,使用查找插件变名 (Version2.8中的NewinVersion2.8),查找所有字典,并迭代列表。在循环中使用查找插件瓦尔斯 (新版本2.5)。并创建列表应用程序。例如
- set_fact:
apps: "{{ apps|default([]) + [lookup('vars', item)] }}"
loop: "{{ query('varnames', '^incl_vars_(.*)$') }}"给出
apps:
- git_repo: https://github.com/philgyford/app2.git
name: app2
- git_repo: https://github.com/philgyford/app1.git
name: app1如果想要,可以将列表转换为字典。
- set_fact:
apps: "{{ dict(_keys|zip(apps)) }}"
vars:
_keys: "{{ apps|map(attribute='name')|list }}"给出
apps:
app1:
git_repo: https://github.com/philgyford/app1.git
name: app1
app2:
git_repo: https://github.com/philgyford/app2.git
name: app2发布于 2018-09-08 17:22:05
自Ansible 2.2以来,include_vars (链接)模块得到了相当大的扩展。
现在可以做这样的事情:
- include_vars:
name: 'apps'
dir: '../vars'
extensions:
- 'yaml'
- 'yml'name是那里的钥匙。从模块页面:
分配包含的vars的变量的名称。如果省略(null),它们将成为顶级vars。
这使您可以转换:
vars/
app1.yml
app2.yml
...附录1.yml:
name: app1
git_repo: https://github.com/philgyford/app1.git
# ...附录2.yml:
name: app2
git_repo: https://github.com/philgyford/app2.git
# ...变成..。
apps:
- name: app1
git_repo: https://github.com/philgyford/app1.git
# ...
- name: app2
git_repo: https://github.com/philgyford/app2.git
# ...https://stackoverflow.com/questions/35554415
复制相似问题