Using Ansible Stat Module to Check File Existence
The Ansible stat module is a powerful tool that allows you to gather information about a file or directory on the remote host. One of the common use cases of the stat module is to check if a file or directory exists on the remote system.
Checking File Existence
To check if a file exists on the remote system using the stat module, you can use the following Ansible task:
- name: Check if file exists
stat:
path: /path/to/file.txt
register: file_status
In this task, the path parameter specifies the location of the file you want to check. The register keyword is used to store the output of the stat module in the file_status variable.
After running this task, you can check the existence of the file by inspecting the file_status.stat.exists attribute. If the file exists, the value will be true, otherwise, it will be false.
Here's an example of how you can use the file_status variable to check if the file exists:
- name: Check if file exists
stat:
path: /path/to/file.txt
register: file_status
- name: Print file existence status
debug:
msg: "File exists: {{ file_status.stat.exists }}"
This will output something like:
TASK [Print file existence status] *********************************************
ok: [localhost] => {
"msg": "File exists: true"
}
If the file does not exist, the output will be:
TASK [Print file existence status] *********************************************
ok: [localhost] => {
"msg": "File exists: false"
}
Checking Directory Existence
You can also use the stat module to check if a directory exists on the remote system. The process is similar to checking file existence, but you'll use the path parameter to specify the directory path:
- name: Check if directory exists
stat:
path: /path/to/directory
register: dir_status
- name: Print directory existence status
debug:
msg: "Directory exists: {{ dir_status.stat.exists }}"
This will output the existence status of the specified directory.
Handling Non-Existent Files or Directories
If the file or directory you're checking does not exist, the stat module will still return a successful result, but the stat.exists attribute will be false. You can use this information to handle the situation accordingly in your Ansible playbook.
For example, you can use a conditional statement to perform different actions based on the existence of the file or directory:
- name: Check if file exists
stat:
path: /path/to/file.txt
register: file_status
- name: Create file if it doesn't exist
file:
path: /path/to/file.txt
state: touch
when: not file_status.stat.exists
In this example, if the file doesn't exist, the file module is used to create it.
By using the stat module, you can easily integrate file and directory existence checks into your Ansible playbooks, allowing you to make informed decisions and automate your infrastructure management tasks more effectively.
