I have to check whether a file exists in /etc/
. If the file exists then I have to skip the task.
Here is the code I am using:
- name: checking th
This can be achieved with the stat module to skip the task when file exists.
- hosts: servers
tasks:
- name: Ansible check file exists.
stat:
path: /etc/issue
register: p
- debug:
msg: "File exists..."
when: p.stat.exists
- debug:
msg: "File not found"
when: p.stat.exists == False
vars:
mypath: "/etc/file.txt"
tasks:
- name: checking the file exists
command: touch file.txt
when: mypath is not exists
If you just want to make sure a certain file exists (f.ex. because it shoud be created in a different way than via ansible) and fail if it doesn't, then you can do this:
- name: sanity check that /some/path/file exists
command: stat /some/path/file
check_mode: no # always run
changed_when: false # doesn't change anything
You can use Ansible stat module to register the file, and when module to apply the condition.
- name: Register file
stat:
path: "/tmp/test_file"
register: file_path
- name: Create file if it doesn't exists
file:
path: "/tmp/test_file"
state: touch
when: file_path.stat.exists == False
A note on relative paths to complement the other answers.
When doing infrastructure as code I'm usually using roles and tasks that accept relative paths, specially for files defined in those roles.
Special variables like playbook_dir and role_path are very useful to create the absolute paths needed to test for existence.