fileloopsansibleline-by-line

ansible read local file to var and then loop read line by line


I would like to create a playbook that reads a local file to a var, Then be able to loop through this var line by line and use the lines in a task.

To get the file content i used:

file_contents: "{{lookup('file', './myfile.txt')}}" 

I tried using:

But I did not get the result i wanted.

any help would be appreciated.


Solution

  • You can use Python built-ins for some types, like strings, for example.

    So this will do the trick for you:

    file_contents_lines: "{{ lookup('file', './aaa.txt').splitlines() }}"
    

    and

    with_items: "{{ file_contents_lines }}"