complex dictionary reference including "item" question

16 views
Skip to first unread message

je...@soundhound.com

unread,
Jul 28, 2017, 3:52:25 PM7/28/17
to Ansible Project
Hi,

I am wondering if it possible to do this kind of form in a playbook. I know how to do it in a template:

If I have some  data of the form:
mydict:
  - entry1:
      data: xyzzy
      filename: scroll.txt
  - entry2:
       data: boom
       filename: sound.txt

things:
  - entry1
  - entry2

In a template, I can to do this:
{% for item in things %}
data = {{ mydict[item]['data'] }}
filename = {{ mydict[item]['filename'] }}
{% endfor %}

What I want to do is in a role task is
- name test copy from variable
  copy:
    content: "{{ mydict[item]['data'] }}
    dest: "{{ target_dir }}/{{ mydict[item]['filename'] }}'
  with_items: things

I can't seem to find the right way to get this to work in a playbook. All my attempts with dots and brackets have failed.
Can someone explain how to represent this in a playbook?

thanks in advance,
jerry

Kai Stian Olstad

unread,
Jul 28, 2017, 4:47:45 PM7/28/17
to ansible...@googlegroups.com
On 28. juli 2017 21:52, je...@soundhound.com wrote:
> I am wondering if it possible to do this kind of form in a playbook. I know
> how to do it in a template:
>
> If I have some data of the form:
> mydict:
> - entry1:
> data: xyzzy
> filename: scroll.txt
> - entry2:
> data: boom
> filename: sound.txt
>
> things:
> - entry1
> - entry2
>
> In a template, I can to do this:
> {% for item in things %}
> data = {{ mydict[item]['data'] }}
> filename = {{ mydict[item]['filename'] }}
> {% endfor %}

Are you sure this work?
This will fail in the same way as your task below.


> What I want to do is in a role task is
> - name test copy from variable
> copy:
> content: "{{ mydict[item]['data'] }}
> dest: "{{ target_dir }}/{{ mydict[item]['filename'] }}'
> with_items: things
>
> I can't seem to find the right way to get this to work in a playbook. All
> my attempts with dots and brackets have failed.
> Can someone explain how to represent this in a playbook?

mydict is not a dict but a list.
So correct syntax is
{{ mydict[item][0]['data'] }} for the first and {{
mydict[item][1]['data'] }} for the second.

If you remove the dashes in front of entry1 and 2 you'll get a dict and
both of your examples will work.


--
Kai Stian Olstad

Mathias Ettinger

unread,
Jul 29, 2017, 3:28:26 AM7/29/17
to Ansible Project
You may be able to make this work with a simple:

- name test copy from variable
copy:

content: "{{ item.data }}
dest: "{{ target_dir }}/{{ item.filename }}'
with_items: "{{ mydict }}"

Why do You need an extra list?

Reply all
Reply to author
Forward
0 new messages