nested variables - again

50 views
Skip to first unread message

mto...@go2uti.com

unread,
Dec 14, 2015, 7:09:55 PM12/14/15
to Ansible Project

I see a lot of discussion about nested variables in Ansible, but I have not yet been able to find a solution to my problem.  So yet again another question about nested variables (pease forgive me if this has been answered before, just point me at the previous discussions).

I want to do define a structure like the following:

STRUCTURE:
    list1:
      - {var1: val1, var2, val2, var3, val3}

    list2:
      - {var1: val1, var2, val2, var3, val3}

    list3:
      - {var1: val1, var2, val2, var3, val3}

Then is a playbook I want to be able to use the value in a variable to select one of the lists:


  vars:
      list: list1

  - debug: msg="var1={{item.var1}}, var2={{item.var2}}, var3={{item.var3}}"
    with_(items,subelements,nested,dict,?)
    - STRUCTURE
    - list

Essentially, I need to have a list of dictionaries, I need to select one of those dictionaries with a key, and then I need to pull the values out of the selected dictionary.  What is the best way to do this?
Thanks,
-Mark

Mike Biancaniello

unread,
Dec 15, 2015, 10:01:04 AM12/15/15
to Ansible Project
Will this do what you need?  using structure[list] instead of trying to nest.

---
- name: stuff
  connection
: local
  gather_facts
: no
  hosts
: localhost

  vars
:
    list
: list1
    structure
:
      list1
:
       
- {var1: "val1", var2: "val2", var3: "val3"}
      list2
:
       
- {var1: "val1", var2: "val2", var3: "val3"}
      list3
:
       
- {var1: "val1", var2: "val2", var3: "val3"}


  tasks
:
 
- name: with_index
    debug
: msg="var1={{item.var1}}, var2={{item.var2}}, var3={{item.var3}}"
    with_items
:
     
- "{{structure[list]}}"



mto...@go2uti.com

unread,
Dec 15, 2015, 11:53:25 AM12/15/15
to Ansible Project
That is close but not quite what I am looking for.  I oversimplified my description of the problem.  I should have said "I need to select one or more of those dictionaries with keys".  So 'list' is a list of one or more keys:
    list:
      - list1
      - list2

And that is where this got complicated.  The temptation is to do something like this:

    - debug: msg="var1={{STRUCTURE.{{item}}.val1}}, var2={{STRUCTURE.{{item}}.val2}}, var3={{STRUCTURE.{{item}}.val3}}"
      with_items:
        - "{{list}}"
 
Of course, I can't have nested braces, but your example gave me the clue I needed to make this work.  Following your lead I came up with this:

    - debug: msg="var1={{STRUCTURE[item].0.val1}}, var2={{STRUCTURE[item].0.val2}}, var3={{STRUCTURE[item].0.val3}}"
      with_items:
        - "{{list}}"

And that got me what I needed!
Thanks for your help!
-Mark
Reply all
Reply to author
Forward
0 new messages