10

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.

Buzut
  • 4,875
  • 4
  • 47
  • 54

2 Answers2

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

The difference between lookup and query is largely that query will always return a list. The default behavior of lookup is to return a string of comma-separated values. lookup can be explicitly configured to return a list using wantlist=True.

  loop: "{{ query('fileglob', 'plugins/*') }}"
  • Additionally, q was introduced as a short form of query
  loop: "{{ q('fileglob', 'plugins/*') }}"

All three options give the same result. See Lookup plugins.

Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • It works perfectly! I couldn't find this in the docs and thought it had been removed as every with_x alternative is presented but this one. Thank you! – Buzut Oct 15 '18 at 12:04
13

From the current Ansible loops doc:

Any with_* statement that requires using lookup within a loop should not be converted to use the loop keyword. For example, instead of doing:

loop: "{{ lookup('fileglob', '*.txt', wantlist=True) }}"

it’s cleaner to keep:

with_fileglob: '*.txt'

Efreeto
  • 2,132
  • 1
  • 24
  • 25
  • Well, this is very important to know, while technically it is not the answer to OP, this is a great practical suggestion, so upvoting. – Drew Dec 20 '22 at 21:14