In this step, you will use the Ansible Stat module to gather information about a file on a remote host.
First, create a new Ansible playbook file called /home/labex/project/stat-module-playbook.yaml
and open it in a text editor.
Add the following content to the playbook file:
- hosts: localhost
tasks:
- name: Get file information
stat:
path: /home/labex/project/file.txt
register: file_info
- name: Print file information
debug:
msg: |
File size: {{ file_info.stat.size }}
Ownership: {{ file_info.stat.uid }}:{{ file_info.stat.gid }}
Permissions: {{ file_info.stat.mode }}
hosts
: This specifies the target host on which to run the playbook. In this case, the playbook will run on the local host because the target host is localhost
.
tasks
: This is a list of tasks to run.
name
: This is the descriptive name for the task that identifies the purpose of the task.
stat
: This Ansible module gathers information about a file on the remote host specified by the path
parameter.
register
: Stores the output of the stat
module in a variable named file_info
for later use.
debug
: Prints debugging information during playbook execution.
msg
: Outputs a message with the file information retrieved using the stat
module, including file size, ownership (UID and GID), and permissions.
In summary, this playbook is designed to retrieve information about a specific file located at /home/labex/project/file.txt
on the local host and print out various details such as size, ownership, and permissions.
Then, create a file called file.txt
in the /home/labex/project
directory.
echo "This is the content of the file." > /home/labex/project/file.txt
Finally, run the playbook with the following command:
ansible-playbook stat-module-playbook.yaml
Observe the output to see the file size, ownership, and permissions of the specified file.
Example output:
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'
PLAY [localhost] ***************************************************************
TASK [Gathering Facts] *********************************************************
ok: [localhost]
TASK [Get file information] ****************************************************
ok: [localhost]
TASK [Print file information] **************************************************
ok: [localhost] => {
"msg": "File size: 33\nOwnership: 5000:5000\nPermissions: 0664\n"
}
PLAY RECAP *********************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0