Loop through var_files variables in ansible
I have a playbook that calls a role and is supposed to import apache vars for websites. The issue is that when I look into ports.conf I only see the line for website1. Website2 is never called. Any help would be greatly appreciated.
---
- hosts: all
vars_files:
- [ "./roles/apache-vhost/vars/website1.yml", "./roles/apache-vhost/vars/website12.yml"]
roles:
- apache-vhost
/roles/apache-vhost/vars/website1.yml
site:
- domain: website1
http_port: 5000
https_port: 6000
./roles/apache-vhost/vars/website2.yml
site:
- domain: website2
http_port: 5001
https_port: 6001
task in playbook is
- name: add http Listeners to ports.conf
lineinfile:
path: /etc/httpd/conf.d/ports.conf
line: 'Listen {{item.http_port}} #{{ item.domain}}'
loop: "{{ site }}"
- name: add https Listeners to ports.conf
lineinfile:
path: /etc/httpd/conf.d/ports.conf
line: 'Listen {{item.https_port}} #{{ item.domain}}'
loop: "{{ site }}"
Thank you.
Solution 1:
The variable site from the 2nd file website2.yml overrides the value from the 1st file website1.yml, e.g.
- hosts: localhost
vars_files:
- website1.yml
- website2.yml
tasks:
- debug:
var: site
gives
site:
- domain: website2
http_port: 5001
https_port: 6001
You'll have to concatenate (merge) the lists in a loop, e.g.
- hosts: localhost
tasks:
- set_fact:
site: "{{ site|default([]) + x.site }}"
loop:
- website1.yml
- website2.yml
vars:
x: "{{ lookup('file', item)|from_yaml }}"
- debug:
var: site
gives
site:
- domain: website1
http_port: 5000
https_port: 6000
- domain: website2
http_port: 5001
https_port: 6001