Ansible: how to read a data file
Let's say I have a data file, each line contains several columns. I want to read the file line per line, select the columns.
My data file
abc 123 def 32 alice ghi 12345 alice bobThe idea is to loop on the file line per line with the splitlines function:
loop: "{{ lookup('file', '/path/to/file').splitlines() }}"Then, for each line, we split the columns based on a separator, and we put the result in a variable:
myvar: "{{ item.split(sep,maxcol).index }}"Where:
- sep is the separator
- maxcol is the maximum number of columns you want to use. If a line contains more columns that maxcol, the last column contains the rest of the line.
- index is the index of the current column.
- name: ... vars: A: "{{ item.split(' ',3).0 }}" B: "{{ item.split(' ',3).1 }}" C: "{{ item.split(' ',3).2 }}" function: ... loop: "{{ lookup('file', '/path/to/file').splitlines() }}"And the result will be:
- Line 1: A="abc", B="123", C=""
- Line 2: A="def", B="32", C="alice"
- Line 3: A="ghi", B="12345", C="alice bob"
Comments