On Friday, 1 December 2017 19.16.19 CET Kai Stian Olstad wrote:
> On Friday, 1 December 2017 18.08.15 CET texas living wrote:
> > I tried, but the title variable does not keep when looping from second row 
> > and on.
> > 
> >     {% for item in csvfile.split("\n") %}
> >     {%   if loop.index == 1 %}
> >     {%     set title = item.split(',') %}
> >     {%   else %}
> >     {%     set list = item.split(",") %}
> >     {{ list[1]|trim() }}:
> >     {{ title[0] }}: {{ list[0]|trim() }}
> >     {{ title[1] }}: {{ list[1]|trim() }}
> >     {{ title[2] }}: {{ list[2]|trim() }}
> >     {{ title[3] }}: {{ list[3]|trim() }}
> >     {{ title[4] }}: {{ list[4]|trim() }}
> >     {{ title[5] }}: {{ list[5]|trim() }}
> >     {%   endif %}
> >     {% endfor %}
> > 
> > The playbook output for task
> > 
> >     TASK [Parse CSV To YAML] 
> > ***********************************************************************************************************
> >     fatal: [localhost]: FAILED! => {"changed": false, "failed": true, 
> > "msg": "AnsibleUndefinedVariable: 'title' is undefined"}
> > 
> >     msg: AnsibleUndefinedVariable: 'title' is undefined
> 
> That's strange since the Jinja documentation have the following about scope:
> "Please keep in mind that it is not possible to set variables inside a block 
> and have them show up outside of it.
> This also applies to loops. The only exception to that rule are if statements 
> which do not introduce a scope."
> 
> Maybe it's a bug.

As a workaround since this i a scope issue, you could set the title outside of 
the for loop.

  {% set title = csvfile.split("\n")[0].split(',') %}
  {% for item in csvfile.split("\n")[1:] %}
  {% set list = item.split(",") %}
  {{ list[1]|trim() }}:
  {{ title[0] }}: {{ list[0]|trim() }}
  {{ title[1] }}: {{ list[1]|trim() }}
  {{ title[2] }}: {{ list[2]|trim() }}
  {{ title[3] }}: {{ list[3]|trim() }}
  {{ title[4] }}: {{ list[4]|trim() }}
  {{ title[5] }}: {{ list[5]|trim() }}
  {% endfor %}

-- 
Kai Stian Olstad

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/4586388.qVVchzYpIa%40x1.
For more options, visit https://groups.google.com/d/optout.

Reply via email to