Score:0

Loop through var_files variables in ansible

us flag

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.

Score:2
br flag

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
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.