After retrieving file metadata using the Ansible Stat module, you can display the information in your playbooks in various ways to suit your needs.
The most common way to display file information is by using the Ansible Debug module. This module allows you to output the contents of variables, including the file metadata retrieved by the Stat module.
Here's an example:
- name: Get file information
ansible.builtin.stat:
path: /path/to/file.txt
register: file_info
- name: Display file information
debug:
msg:
- "File path: {{ file_info.stat.path }}"
- "File exists: {{ file_info.stat.exists }}"
- "File type: {{ 'directory' if file_info.stat.isdir else 'file' }}"
- "File size: {{ file_info.stat.size }} bytes"
- "File owner: {{ file_info.stat.owner }}"
- "File permissions: {{ file_info.stat.mode }}"
- "File modification time: {{ file_info.stat.mtime }}"
In this example, the file metadata is stored in the file_info
variable, and the debug
module is used to display the information in a formatted message.
You can also use the file metadata to perform conditional checks in your playbooks. This can be useful for automating tasks based on the state of files and directories.
For example, you can check if a file exists before attempting to copy or modify it:
- name: Check if file exists
ansible.builtin.stat:
path: /path/to/file.txt
register: file_info
- name: Copy file
ansible.builtin.copy:
src: /path/to/source.txt
dest: /path/to/file.txt
when: file_info.stat.exists
In this example, the Stat module is used to check if the file at /path/to/file.txt
exists. The copy
task is only executed if the file exists, as determined by the file_info.stat.exists
condition.
You can also store the file metadata retrieved by the Stat module for later use in your playbooks. This can be useful for generating reports, comparing file states across multiple hosts, or automating other tasks.
For example, you can store the file metadata in a variable and use it in a subsequent task:
- name: Get file information
ansible.builtin.stat:
path: /path/to/file.txt
register: file_info
- name: Print file modification time
debug:
msg: "File modification time: {{ file_info.stat.mtime }}"
In this example, the file metadata is stored in the file_info
variable, which can then be accessed in subsequent tasks, such as the debug
task that prints the file modification time.