Using Ansible Stat Module to Get File Modification Timestamp
The Ansible stat module is a powerful tool that allows you to retrieve information about files and directories on the remote hosts. One of the key pieces of information that the stat module can provide is the modification timestamp of a file.
Understanding the Stat Module
The stat module in Ansible is used to obtain information about a file or directory on the remote host. It can retrieve various attributes of the file or directory, such as:
- File type (regular file, directory, symlink, etc.)
- File permissions
- File owner and group
- File size
- File modification and access times
To get the file modification timestamp using the stat module, you can use the modtime or mtime (modification time) parameter.
Retrieving the File Modification Timestamp
Here's an example of how to use the stat module to get the modification timestamp of a file:
- name: Get file modification timestamp
stat:
path: /path/to/file.txt
register: file_stats
- name: Print file modification timestamp
debug:
msg: "File modification timestamp: {{ file_stats.stat.mtime }}"
In this example, the stat module is used to retrieve information about the file located at /path/to/file.txt. The retrieved information is stored in the file_stats variable. The mtime parameter in the file_stats.stat object contains the modification timestamp of the file, which is then printed using the debug module.
The mtime value represents the number of seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). If you need to display the timestamp in a more human-readable format, you can use the ansible.builtin.set_fact module to convert the timestamp:
- name: Get file modification timestamp
stat:
path: /path/to/file.txt
register: file_stats
- name: Convert modification timestamp to human-readable format
set_fact:
file_modified: "{{ file_stats.stat.mtime | human_readable_timestamp }}"
- name: Print file modification timestamp
debug:
msg: "File modification timestamp: {{ file_modified }}"
In this example, the human_readable_timestamp filter is used to convert the mtime value to a human-readable format, such as "2023-04-18 14:30:00".
Visualizing the Workflow
Here's a Mermaid diagram that illustrates the workflow of using the Ansible stat module to retrieve the file modification timestamp:
This diagram shows the step-by-step process of using the stat module to get the file modification timestamp, including the optional step of converting the timestamp to a human-readable format.
By using the Ansible stat module, you can easily retrieve the modification timestamp of files on remote hosts, which can be useful for various tasks, such as monitoring file changes, automating backups, or tracking file modifications in your infrastructure.
