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.
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.
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.
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'] }}"
In other words, if roles/role1/tasks
looks like this:
---
- set_fact:
logfiles: "{{ logfiles|default([]) + ['/var/log/role1.log'] }}"
And roles/role2/tasks
looks like this:
---
- 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
Will produce this output:
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