Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible looping through files

Prior to Ansible 2.5, the syntax for loops used to be with_x. Starting at 2.5, loop is favored and with_x basically disappeared from the docs.

Still, the docs mention exemples of how to replace with_x with loop. But I'm clueless as to how we're now supposed to loop through a directory of files.

Let's say I need to upload all the files within a given dir, I used to use with_fileglob.

- name: Install local checks
  copy:
    src: "{{ item }}"
    dest: /etc/sensu/plugins/
    owner: sensu
    group: sensu
    mode: 0744
  with_fileglob:
    - plugins/*

So what's the modern equivalent? Is it even possible? I know I still can use with_fileglob but as I'm writing new roles, I'd better have them future-proof.

like image 906
Buzut Avatar asked Oct 15 '18 11:10

Buzut


People also ask

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

Introduction to Ansible Loop. 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 you use 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.

What is Loop_var in Ansible?

Defining inner and outer variable names with loop_var However, by default Ansible sets the loop variable item for each loop. This means the inner, nested loop will overwrite the value of item from the outer loop. You can specify the name of the variable for each loop using loop_var with loop_control .


1 Answers

The equivalent is

    loop: "{{ lookup('fileglob', 'plugins/*', wantlist=True) }}"

Here is the doc.

like image 155
Vladimir Botka Avatar answered Oct 02 '22 09:10

Vladimir Botka