How to check if a file exists in Ansible?
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 the file exists
command: touch file.txt
when: $(! -s /etc/file.txt)
You can first check that the destination file exists or not and then make a decision based on the output of its result:
tasks:
- name: Check that the somefile.conf exists
stat:
path: /etc/file.txt
register: stat_result
- name: Create the file, if it doesnt exist already
file:
path: /etc/file.txt
state: touch
when: not stat_result.stat.exists
The stat module will do this as well as obtain a lot of other information for files. From the example documentation:
- stat: path=/path/to/something
register: p
- debug: msg="Path exists and is a directory"
when: p.stat.isdir is defined and p.stat.isdir
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
In general you would do this with the stat module. But the command module has the creates
option which makes this very simple:
- name: touch file
command: touch /etc/file.txt
args:
creates: /etc/file.txt
I guess your touch command is just an example? Best practice would be to not check anything at all and let ansible do its job - with the correct module. So if you want to ensure the file exists you would use the file module:
- name: make sure file exists
file:
path: /etc/file.txt
state: touch