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

Komar Patel picture Komar Patel · Jan 23, 2018 · Viewed 7.2k times · Source

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:

  • with_file
  • with_item
  • with_lines

But I did not get the result i wanted.

any help would be appreciated.

Answer

Konstantin Suvorov picture Konstantin Suvorov · Jan 23, 2018

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 }}"