Ansible with_dict expects a dict

TechplexEngineer picture TechplexEngineer · Jul 28, 2017 · Viewed 16.9k times · Source

I know this question has been asked many times before but I must be missing something here!

This is a minimal playbook to reproduce the issue.

Here is the playbook:

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

Here is the output:

$ 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

I would expect the item variable printed in task2 to contain (for example):

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

What are we missing?

Answer

kfreezy picture kfreezy · Jul 28, 2017

Looks like Ansible's documentation needs updated or you've found a bug. http://docs.ansible.com/ansible/latest/playbooks_loops.html#looping-over-hashes uses your with_dict syntax but it seems like that doesn't work anymore. The dictionary needs to be on the same line as with_dict.

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