How can I iterate over each line inside a file with an option?

I am looking for something that would be similar to with_items: but that would get a list of elements from the file instead of including it in the playbook file.

How can I make it out of reach?

+13
source share
4 answers

I managed to find an easy alternative:

 - debug: msg="{{item}}" with_lines: cat files/branches.txt 
+23
source

Let's say you have a file like

 item 1 item 2 item 3 

And you want to install these elements. Just load the contents of the file into a variable using register.And use this variable with with_items . Make sure your file has one item per line.

 --- - hosts: your-host remote_user: your-remote_user tasks: - name: get the file contents command: cat /path/to/your/file register: my_items - name: install these items pip: name:{{item}} with_items: my_items.stdout_lines 
+11
source

I am surprised that no one mentioned the search , I think this is exactly what you want.

It reads the content that you want to use in your game book, but do not want to include in the game book from files, channel , csv , redis , etc. from your local host computer (not from a remote computer, this is important since in most cases this content is next to your playbook on the local computer) and it works with ANSIBLE LOOP.

 --- - hosts: localhost gather_facts: no tasks: - name: Loop over lines in a file debug: var: item with_lines: cat "./files/lines" 

with_lines here is actually a loop with searching for strings, to see how the search for lines works, look at the code here , it just runs any commands that you give it (so that you can give it any such as echo, cat, etc. ), then split the output into lines and return them.

There are many powerful searches to get a complete list; check the search plugins folder .

+7
source

The latter Ansible recommends a loop instead of with_something . It can be used in combination with lookup and splitlines() , as Ikar Pokhorski pointed out:

 - debug: msg="{{item}}" loop: "{{ lookup('file', 'files/branches.txt').splitlines() }}" 

files/branches.txt should be relative to the play

+2
source

All Articles