Search code examples
variablesansibleload

Is it possible to combine values of same variable name mentioned in seperate vars file in Ansible


I have two variable files app1.yml and app2.yml having the same variable name viz dbconn

cat app1.yml
dbconn:
  - host1 port1

cat app2.yml
dbconn:
  - host4 port4
  - host5 port5

cat main.yml

   - name: Load Variable Files
     include_vars: "{{ playbook_dir }}/{{ item }}.yml"
     loop: 
       - app1
       - app2
     run_once: yes

   - debug:
       msg: "{{ dbconn }}"

My expectation is that variable dbconn to have values from both the variable files i.e

  - host1 port1
  - host4 port4
  - host5 port5

However, it prints only the last loaded variable file values i.e - host4 port4 and - host5 port5

Can you please suggest?


Solution

  • Concatenate the lists in the loop. For example,

        - set_fact:
            dbconn: "{{ dbconn|d([]) + (lookup('file', item)|from_yaml).dbconn }}"
          loop:
            - app1.yml
            - app2.yml
    

    gives

    dbconn:
      - host1 port1
      - host4 port4
      - host5 port5