Ansible:循环遍历嵌套的字典变量

时间:2020-03-27 17:52:03

标签: ansible

我有以下带有嵌套字典的vars.yml文件:

hosts:
  server_1:    
    apps:
      - x1
      - x2
      - x3
      - x4
      - x5
    storage:
      -
      -
    cpu:
      -
      -
  server_2:    
    apps:
      - y1
      - y2
      - y3
      - y4
      - y5
    storage:
      -
      -
    cpu:
      -
      -
server_N:    
    apps:
      - n1
      - n2
      - n3
      - n4
      - n5

我想在下面的示例剧本中通过变量循环使用它,以便在dict上多次执行任务:

- hosts: localhost
  gather_facts: no
  vars_files:
    - vars.yml

  tasks:
    - name: Install apps
      debug:
          msg: "{{ item.value }}"
          msg: "{{ item.value.apps }}"
      with_dict: "{{ hosts }}"

我想将它们用作变量,并获得服务器和应用程序相关的结果循环迭代。

1. msg: "server_1"
   msg: "x1"
2. msg: "server_1"
   msg: "x2"
3.  msg: "server_1"
   msg: "x3"
....etc
6. msg: "server_2"
   msg: "y1"
7. msg: "server_2"
   msg: "y2"
....etc

我想你明白了。 此外,vars.yml文件中可用的“ server_N”数量无关紧要!

获得此结果的最简单,正确的方法是什么?

2 个答案:

答案 0 :(得分:0)

正确的方法是将该信息放入文件host_vars/server1host_vars/server2等中。

# this is host_vars/server1
apps:
  - x1
  - x2
  - x3
  - x4
  - x5
storage:
  -
  -
cpu:
  -
  -

然后,您的剧本如下所示:

- hosts: all
  gather_facts: no

  tasks:
  - name: Install apps
    debug:
      msg: "{{ item }}"
    with_items: "{{ apps }}"
    delegate_to: localhost      # if really necessary

答案 1 :(得分:0)

任务

    - debug:
        msg: "{{ item.0.key }} {{ item.1 }}"
      with_subelements:
        - "{{ hosts|dict2items }}"
        - value.apps

给予

    "msg": "server_N n1"
    "msg": "server_N n2"
    "msg": "server_N n3"
    "msg": "server_N n4"
    "msg": "server_N n5"
    "msg": "server_1 x1"
    "msg": "server_1 x2"
    "msg": "server_1 x3"
    "msg": "server_1 x4"
    "msg": "server_1 x5"
    "msg": "server_2 y1"
    "msg": "server_2 y2"
    "msg": "server_2 y3"
    "msg": "server_2 y4"
    "msg": "server_2 y5"