是否可以合并anisible group_vars,如果可以的话,请问我如何解决

时间:2019-06-22 15:23:25

标签: ansible ansible-2.x ansible-inventory ansible-facts ansible-template

实际上我有group_vars,我需要合并这些vars,您能帮我吗?

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 

如何整合这些变量以及如何在剧本中调用合并的变量

2 个答案:

答案 0 :(得分:1)

让我们简化数据

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

带有库存文件

[eu]
test_01

[us]
test_02

下面的戏

- 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

给予(删节的)

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"
    }
}

这是您要找的吗?

答案 1 :(得分:0)

感谢回复我的帖子,但实际上我必须在group_vars上工作,而不是在主机vars上工作。