Dict subelements containing arrays

32 views
Skip to first unread message

Jeff Hardy

unread,
Apr 4, 2016, 10:18:56 AM4/4/16
to Ansible Project
Hello all,

I am trying to build a play that allows for variable subelement selection, and subsequent iteration over array contained therein.  The following test playbook hopefully illustrates the situation:

---
- hosts: localhost
  connection: local
  gather_facts: false
  vars:
    foo:
      bar:
        - name: somebar1
          desc: somebar1text
        - name: somebar2
          desc: somebar2text
      baz:
        - name: somebaz1
          desc: somebaz1test

  tasks:
    - debug: var=foo.bar

    - debug: var=foo.{{select}}

    #- debug: var={{item}}
    #  with_items: "foo.{{select}}"

    - command: echo "{{item.name}}"
      with_items: "foo.{{select}}"


When select is passed in with -e "select=bar" or baz, the debug statements look fine, but the final with_items results in:

fatal: [localhost]: FAILED! => {"failed": true, "msg": "'unicode object' has no attribute 'name'"}

When I uncomment the third debug statement, output seems to indicate that with_items is not returning the elements of the array, but the entire array:

ok: [localhost] => (item=foo.bar) => {
    "foo.bar": [
        {
            "desc": "somebar1text", 
            "name": "somebar1"
        }, 
        {
            "desc": "somebar2text", 
            "name": "somebar2"
        }
    ], 
    "item": "foo.bar"
}


I have looked at with_dict and with_subelements and a few others, but they do not seem to fit the situation.  I have some workarounds in mind that are less than pretty.  Can someone point me in the right direction?  Thank you.

Jeff Hardy

unread,
Apr 14, 2016, 8:54:45 PM4/14/16
to Ansible Project
Ultimately, using alternate notation solves this:

- debug: var="{{item}}"
  with_items: "{{foo[select]}}"
Reply all
Reply to author
Forward
0 new messages