在 Ansible 中,在一个角色中,我有这样的 vars 文件:
vars/
app1.yml
app2.yml
每个文件都包含特定于应用程序/网站的变量,如下所示:
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
array.
如果这是使此类事情成为可能的唯一方法,我愿意稍微重新安排一些事情。
你不能这样做。变量总是会覆盖同名的变量。对于这个精确的设置,你唯一能做的就是编写你自己的 vars 插件 http://docs.ansible.com/ansible/developing_plugins.html#vars-plugins它读取这些文件并将它们合并到一个数组中。
如果您愿意更改应用程序定义的结构,您可以使用散列和设置你的hash_behavior=merge https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-hash-behaviour。在每个 vars 文件中,您都会有一个如下定义:
apps:
app1:
git_repo: https://github.com/philgyford/app1.git
apps:
app2:
git_repo: https://github.com/philgyford/app2.git
当 Ansible 加载这两个文件时,它会自动将其合并到一起:
apps:
app1:
git_repo: https://github.com/philgyford/app1.git
app2:
git_repo: https://github.com/philgyford/app2.git</pre>
但请注意hash_behavior=merge
从根本上改变了 Ansible 在全局范围内的默认行为。确保您的所有角色都没有此设置的问题。文档提到:
我们通常建议不要使用此设置,除非您认为绝对需要它
如果您仍然使用 Ansible 1,您可以使用我的旧插件之一:include_vars_merged https://gist.github.com/udondan/b730206056a018cf9838。基本上这增加了以下行为hash_behavior=merge
仅针对单个任务。
I have not yet looked into migrating this to Ansible 2 though and currently it looks like I won't have the need for it any longer.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)