Question:
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:
1 2 3 |
- 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
1 2 3 4 5 |
- 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.
Answer:
Below code seems to work, except the optional file I was looking was in my local machine, so I had to run stat through local_action and set become: no
for that particular tasks, so ansible wouldn’t attempt to do sudo in my local machine and error with: “sudo: a password is required\n”
1 2 3 4 5 6 |
- local_action: stat path=/home/user/optional/file.yml register: optional_file become: no - include: /home/user/optional/file.yml when: optional_file.stat.exists |