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!
You can achieve your requirement using the new
loop
syntax and calling the lookup plugin directly, then sorting the result:References:
fileglob
lookupsort
filter