2017-07-28 88 views
2

我知道这个问题之前已经被问过很多次了,但是我必须在这里错过一些东西!Ansible with_dict期待一个字典

这是重现问题的最小手册。

这里是剧本:

--- 
- hosts: 
    - localhost 
    gather_facts: false 
    vars: 
    zones_hash: 
     location1: 
     id: 1 
     control_prefix: '10.1.254' 
     data_prefix: '10.1.100' 
     location2: 
     id: 2 
     control_prefix: '10.2.254' 
     data_prefix: '10.2.100' 
    tasks: 
    - name: "test1" 
     debug: var="zones_hash" 

    - name: "test2" 
     debug: var="item" 
     with_dict: 
     - "{{ zones_hash }}" 

这里是输出:

$ ansible --version 
ansible 2.3.1.0 
    config file = /home/configs/_ansible/ansible.cfg 
    configured module search path = Default w/o overrides 
    python version = 2.7.5 (default, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] 
$ ansible-playbook playbook.yml 

PLAY [localhost] ******************************************************************************* 

TASK [test1] *********************************************************************************** 
ok: [localhost] => { 
    "zones_hash": { 
     "location1": { 
      "control_prefix": "10.1.254", 
      "data_prefix": "10.1.100", 
      "id": 1 
     }, 
     "location2": { 
      "control_prefix": "10.2.254", 
      "data_prefix": "10.2.100", 
      "id": 2 
     } 
    } 
} 

TASK [test2] *********************************************************************************** 
fatal: [localhost]: FAILED! => {"failed": true, "msg": "with_dict expects a dict"} 

PLAY RECAP ************************************************************************************* 
localhost     : ok=1 changed=0 unreachable=0 failed=1 

我期望在TASK2打印的项目变量包含(例如):

key: location1 
value: { 
    id: 1 
    control_prefix: '10.1.254' 
    data_prefix: '10.1.100' 
} 

我们缺少什么?

回答

2
with_dict: 
    - "{{ zones_hash }}" 

声明了一个列表用字典作为第一指标,Ansible理所当然地抱怨,因为它期望的字典。

解决方案kfreezy提到的作品,因为它实际上给出了一个字典with_dict,而不是一个列表:

with_dict: "{{ zones_hash }}"