How to run Ansible with_fileglob in alpabetical order?
Asked Answered
M

1

5

I'm trying to build a system that will include tasks from a directory in alphabetical order. Let's say I have the following files in a directory:

01-task.yml
02-task.yml
..
10-task.yml

I want ansible to include these tasks in order (01, 02, 03, etc). In testing if fileglob is in order, I ran the following:

- hosts: localhost
  tasks:
  - debug:
      msg: "File {{ item }}"
    with_fileglob: "<ansible directory>/testing/files/*"

And get the output in random order:

File <ansible directory>/testing/files/03-task.yml
File <ansible directory>/testing/files/05-task.yml
File <ansible directory>/testing/files/08-task.yml
File <ansible directory>/testing/files/09-task.yml
File <ansible directory>/testing/files/02-task.yml
File <ansible directory>/testing/files/10-task.yml
File <ansible directory>/testing/files/07-task.yml
File <ansible directory>/testing/files/01-task.yml
File <ansible directory>/testing/files/06-task.yml
File <ansible directory>/testing/files/04-task.yml

I'm struggling to come up with how I can sort the file globbing. I'm hoping to avoid a task for set_fact in a loop to create an array, another task to sort, and another task to include the files. Is there a more efficient way that I'm missing?

EDIT: Thanks to Zeitounator I have a final working code of:

- hosts: localhost
  tasks:
  - name: Test Import
    include_tasks: "{{ item }}"
    loop: "{{ query('fileglob', \"<ansible directory>/testing/files/*\")|sort }}"

Each task file is just simply:

- debug: msg="This Is File [1-10]"

Which outputs in the correct order perfectly!

Marinamarinade answered 3/12, 2019 at 17:4 Comment(0)
L
6

You can achieve your requirement using the new loop syntax and calling the lookup plugin directly, then sorting the result:

- hosts: localhost
  tasks:
  - debug:
      msg: "File {{ item }}"
    loop: "{{ query('fileglob', '<ansible directory>/testing/files/*') | sort }}"

References:

Lapides answered 3/12, 2019 at 17:21 Comment(1)
Perfect! Thank you!Marinamarinade

© 2022 - 2024 — McMap. All rights reserved.