how to iterate csv file in ansible

2020-04-14 02:43发布

问题:

i have a jinja2 template including a section that need data from a csv file how can i read a csv file and split it into a list then iterate it in the jinja2 template? sth. like this:

{% for line in csv_data %}
    {{ line[0] }} = {{ line[1] }}
{% endfor %}

in my task file, i am trying to use lookup to read the csv file into csv_data, but it seems lookup can only query and get one line not the whole file, or just the whole file in raw format

vars:
  csv_data: "{{ lookup('file', 'test.csv') }}"

回答1:

figured a not so good method:

{% for line in csv_data.split("\n") %}
       {% set list = line.split(",") %}
       {{ list[0] }}={{ list[1] }}
{% endfor %}