Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible include task only if file exists

Tags:

ansible

I'm trying to include a file only if it exists. This allows for custom "tasks/roles" between existing "tasks/roles" if needed by the user of my role. I found this:

- include: ...   when: condition 

But the Ansible docs state that:

"All the tasks get evaluated, but the conditional is applied to each and every task" - http://docs.ansible.com/playbooks_conditionals.html#applying-when-to-roles-and-includes

So

- stat: path=/home/user/optional/file.yml   register: optional_file - include: /home/user/optional/file.yml   when: optional_file.stat.exists 

Will fail if the file being included doesn't exist. I guess there might be another mechanism for allowing a user to add tasks to an existing recipe. I can't let the user to add a role after mine, because they wouldn't have control of the order: their role will be executed after mine.

like image 354
Leonel Galán Avatar asked Jan 23 '15 22:01

Leonel Galán


People also ask

How to check if file exists Ansible?

To check whether the destination file exists and then run tasks based on its status, we can use the Ansible's stat module (or win_stat for Windows targets). With this module we can identify not only whether the destination path exists or not but also if it is a regular file, a directory or a symbolic link.

What is Changed_when in Ansible?

Ansible lets you define when a particular task has “changed” a remote node using the changed_when conditional. This lets you determine, based on return codes or output, whether a change should be reported in Ansible statistics and whether a handler should be triggered or not.

What is stat module in Ansible?

In Linux, the stat command is a command-line utility that provides detailed information about filesystems or files. Ansible, considered the most diverse and popular automation tool, provides a module for fetching file and file system information as native Linux stat command.

How do I find files in Ansible?

Checking if a File Exists in Ansible The stat module uses the following syntax: --- - name: Playbook name hosts: all tasks: - name: Task name stat: path: [path to the file or directory you want to check] register: register_name ...


1 Answers

The with_first_found conditional can accomplish this without a stat or local_action. This conditional will go through a list of local files and execute the task with item set to the path of the first file that exists. Including skip: true on the with_first_found options will prevent it from failing if the file does not exist.

Example:

- hosts: localhost   connection: local   gather_facts: false    tasks:     - include: "{{ item }}"       with_first_found:         - files:             - /home/user/optional/file.yml           skip: true 
like image 124
Dave Konopka Avatar answered Oct 18 '22 01:10

Dave Konopka