When building playbooks and tasks, you may find you want to check the status of a host before you attempt to perform a particular action upon it.
You wouldn’t want it to attempt to perform an action which would fail because something is missing, you’d want it to check first. Although you can use conditionals to handle the situation and perhaps continue, this is beyond the scope of this article. Instead we’re just looking at using two Ansible methods “stat” and “assert”.
So, stat is used to gather information about a file directory on the managed host. It doesn’t change anything on the host and you can use it to check if a path exists, whether it is a file or directory, or check gather its permissions, owner, size, checksum etc.
You can then use assert to check if that the condition (gathered by stat) is true or false, and then if false fail with an optional message saying why. Assert is useful to validate that a host is in the state that your playbook has been coded to, before it conducts any actions.
Example
The below example checks if the /etc/ssh/sshd_config file exists and if it is a regular file.
- name: Check SSH configuration file
ansible.builtin.stat:
path: /etc/ssh/sshd_config
register: ssh_config
- name: Confirm SSH configuration file is present
ansible.builtin.assert:
that:
- ssh_config.stat.exists
- ssh_config.stat.isreg
success_msg: "SSH configuration file exists"
fail_msg: "SSH configuration file is missing or is not a regular file"

So from what we can see, stat has collected that file /etc/ssh/sshd_config does indeed exist and this is held within the ssh_config register (variable) as ssh_config.stat.exists (in this case with the value “true”) and then that it is a regular file (i.e. not a directory, or symlink or the like), and that is again in ssh_config as ssh_config.stat.isreg.
Now the assert comes into play. It checks if these two conditions ssh_config.stat.exists and ssh_config.stat.isreg are true or false; and prints a message either way.
If we were then to change the ansible to instead look for a non-existent file called: /etc/ssh/sshd_config, we’d get the following:

In which case we can assert that the host is not in the state we expect and therefore the playbook (for that host or any other host) should fail because it doesn’t match the state we would expect!