Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop over each line inside a file with ansible?

Tags:

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

How can I do this in ansible?

like image 604
sorin Avatar asked Nov 05 '15 10:11

sorin


People also ask

How do you do nested loops in Ansible?

Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task. Now we can create nested loops using with_nested.

Which loop can be used to iterate over files in a directory Ansible?

Looping over Filetrees. with_filetree recursively matches all files in a directory tree, enabling you to template a complete tree of files on a target system while retaining permissions and ownership.

What is loop control in Ansible?

Ansible loop is used to repeat any task or a part of code multiple times in an Ansible-playbook. It includes the creation of multiple users using the user module, installing multiple packages using apt or yum module or changing permissions on several files or folders using the file module.

How do I run an Ansible loop?

The loop keyword is usually used to create simple and standard loops that iterate through several items. The with_* keyword is used with a number of lookup plugins when iterating through values. Lookup plugins enable Ansible to access information from external sources such as external data stores, filesystems etc.


2 Answers

I managed to find an easy alternative:

- debug: msg="{{item}}"   with_lines: cat files/branches.txt 
like image 164
sorin Avatar answered Sep 19 '22 15:09

sorin


Latest Ansible recommends loop instead of with_something. It can be used in combination with lookup and splitlines(), as Ikar Pohorský pointed out:

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

files/branches.txt should be relative to the playbook

like image 33
Cristian Avatar answered Sep 21 '22 15:09

Cristian