Practical Examples of Stat Module
Now that we have a solid understanding of the Ansible Stat module and the file attributes it can retrieve, let's explore some practical examples of how you can use this module in your Ansible playbooks.
Checking for File Existence Before Copying
One common use case for the Stat module is to check if a file exists before attempting to copy it to the target host. This can help you avoid errors and ensure that your playbook runs smoothly.
- name: Check if source file exists
stat:
path: /path/to/source/file.txt
register: source_file
- name: Copy file if it exists
copy:
src: /path/to/source/file.txt
dest: /path/to/destination/file.txt
when: source_file.stat.exists
In this example, the Stat module is used to check if the source file exists. If the file exists, the copy
task is executed to copy the file to the destination. The when
condition ensures that the copy task is only executed when the source file exists.
Enforcing File Permissions
Another common use case for the Stat module is to ensure that files and directories have the correct permissions. You can use the stat.mode
attribute to check the current permissions and then set the desired permissions using the file
module.
- name: Ensure file permissions
file:
path: /path/to/file.txt
mode: '0644'
when: file_info.stat.mode != '0644'
register: file_info
In this example, the Stat module is used to check the current file permissions. If the permissions do not match the desired value of 0644
, the file
module is used to set the correct permissions.
Conditional Execution Based on File Type
The Stat module can also be used to make decisions based on the type of the file or directory. For example, you can perform different actions for regular files and directories.
- name: Check file type
stat:
path: /path/to/file_or_directory
register: path_info
- name: Handle regular file
copy:
src: /path/to/file_or_directory
dest: /path/to/destination
when: path_info.stat.isfile
- name: Handle directory
unarchive:
src: /path/to/file_or_directory
dest: /path/to/destination
when: path_info.stat.isdir
In this example, the Stat module is used to determine the type of the file or directory at the specified path. Based on the file type, either the copy
task (for regular files) or the unarchive
task (for directories) is executed.
These are just a few examples of how you can use the Ansible Stat module in your playbooks. By leveraging the file metadata provided by this module, you can create more robust and intelligent automation workflows that can adapt to the specific conditions of your target systems.