Search code examples
ansibleansible-2.xansible-inventoryansible-factsansible-template

Is it possible to merge anisible group_vars, if possible can you hlep me how to solve


Actually I have group_vars, I need to merge those vars, can you help me.

group_vars/eu/main.yaml
mgmt_routes:
 Tok:
  -  ip: 172.22.203.253
     netmask: 255.255.255.255 

group_vars/all/main.yaml     
mgmt_routes:
 all:
  -  ip: 172.18.0.70
     netmask: 255.255.255.255 
  -  ip: 172.18.3.50
     netmask: 255.255.255.255 

How can i integrate those variables and How can i call merged variables in playbook


Solution

  • Let's simplify the data

    $ cat group_vars/all/main.yml 
    mgmt_routes:
     all: ALL ROUTES
    $ cat group_vars/eu/main.yml 
    mgmt_routes:
     Tok: TOK ROUTES
    

    With the inventory file

    [eu]
    test_01
    
    [us]
    test_02
    

    The plays below

    - hosts: test_01
      tasks:
        - debug:
            var: mgmt_routes
    
    - hosts: test_02
      tasks:
        - debug:
            var: mgmt_routes
        - set_fact:
            all_routes_list: "{{ hostvars|
                                 json_query('*.mgmt_routes')|
                                 unique }}"
        - set_fact:
            all_routes_dict: "{{ all_routes_dict|
                                 default({})|
                                 combine(item) }}"
          loop: "{{ all_routes_list }}"
        - debug:
            var: all_routes_dict
    

    give (abridged)

    ok: [test_01] => {
        "mgmt_routes": {
            "Tok": "TOK ROUTES"
        }
    }
    
    ok: [test_02] => {
        "mgmt_routes": {
            "all": "ALL ROUTES"
        }
    }
    
    ok: [test_02] => {
        "all_routes_dict": {
            "Tok": "TOK ROUTES", 
            "all": "ALL ROUTES"
        }
    }
    

    Is this what you're looking for?