在 Ansible 中,如何将来自活动角色的变量组合到一个数组中? [英] In Ansible, how to combine variables from active roles into one array?
问题描述
查看在 Ansible 中,如何将来自不同文件的变量合并到一个数组中?" 答案之一建议使用 include_vars 将多个来源的变量放入一个数组中,这几乎我需要但不完全是.
Looking at "In Ansible, how to combine variables from separate files into one array?" one of the answers suggests using include_vars to get variables from several sources into one array, this is almost what I need but not quite.
我正在设置 cloudfront_logging,它需要 awslogs_logs:
数组中的项目.我希望能够为我有活动的角色添加到这个数组中,所以 Syslog 是我的共同角色,但如果我有一个 php 角色,我希望它包含 php 日志.
I'm setting up cloudfront_logging which requires items in a awslogs_logs:
array. I'd like to be able to add to this array for the roles that I have active, so Syslog in my common role but if I have a php role, I'd like it to include the php logs.
我想我可以让 include_vars
为所有角色工作,但我看不出如何让它只为包含在构建中的角色工作.因此,如果我包含 php 角色,则包含 php 日志,但如果不包含则不包含.
I think I could get include_vars
to work for all roles, but I can't see how to get this to work for only the roles included in a build. So if I include the php role, include the php logs but not if it is not included.
当然,我可以静态地将数组包含在顶层,但这似乎在架构上有点偏离,因为您希望角色能够处理自己的日志记录.
I could, of course, include the array at the top level statically but that seems like it is architecturally a bit off as you'd expect a role to be able to deal with its' own logging.
推荐答案
您的角色可以使用 set_fact
任务将信息附加到变量.例如,假设您希望角色能够在 logfiles
事实中注册日志文件的路径;你可以在每个角色中做这样的事情:
Your roles can use a set_fact
task to append information to a variable. For example, let's say you want roles to be able to register paths to log files in the logfiles
fact; you could do something like this in each role:
- set_fact:
logfiles: "{{ logfiles|default([]) + ['/var/log/something.log', '/var/log/anotherthing.log'] }}"
换句话说,如果 roles/role1/tasks
看起来像这样:
In other words, if roles/role1/tasks
looks like this:
---
- set_fact:
logfiles: "{{ logfiles|default([]) + ['/var/log/role1.log'] }}"
roles/role2/tasks
看起来像这样:
---
- set_fact:
logfiles: "{{ logfiles|default([]) + ['/var/log/role2.log'] }}"
然后是一个看起来像这样的剧本:
Then a playbook that looks like this:
---
- hosts: localhost
gather_facts: false
roles:
- role1
- role2
tasks:
- debug:
var: logfiles
将产生此输出:
PLAY [localhost] ******************************************************************************
TASK [role1 : set_fact] ***********************************************************************
ok: [localhost]
TASK [role2 : set_fact] ***********************************************************************
ok: [localhost]
TASK [debug] **********************************************************************************
ok: [localhost] => {
"logfiles": [
"/var/log/role1.log",
"/var/log/role2.log"
]
}
PLAY RECAP ************************************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
这篇关于在 Ansible 中,如何将来自活动角色的变量组合到一个数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!