How to check if a directory exists in Ansible?
I’m going to show you a live Playbook and some simple Ansible code.
I’m Luca Berton and welcome to today’s episode of Ansible Pilot.
Ansible check directory exists
Today we’re talking about the Ansible module stat.
The full name is ansible.builtin.stat, which means that is part of the collection of modules “builtin” with ansible and shipped with it.
It’s a module pretty stable and out for years.
It works in a different variety of operating systems.
It retrieves a file entry or a file system status.
For Windows target use the [ansible.windows.win_stat](/articles/check-if-a-directory-exists-on-windows-like-systems-ansible-module-winstat) module instead.
Main parameters and return values
path_string_
The only mandatory parameter is “path” which is the filesystem full path of the object to check.
* stat _complex_
The module returns a complex object, the property that is interesting for us is “isdir”. This attribute is “true” if the object is a directory.
Demo
Let’s jump in a real-life playbook to check if a directory exists with Ansible.
code
- directory_check_exists.yml
``yaml
---
- name: check if the directory exists
hosts: all
become: false
vars:
directory: "/tmp"
tasks:
- name: Check if the directory exists
ansible.builtin.stat:
path: "{{ directory }}"
register: dir_to_check
- name: Directory found
ansible.builtin.debug:
msg: "Directory {{ directory }} present"
when: dir_to_check.stat.isdir is defined and dir_to_check.stat.isdir
``
[code with ❤️ in GitHub](https://github.com/lucab85/ansible-pilot/tree/master/check%20directory%20exists)
Conclusion
Now you know better the Ansible module stat and you could use it successfully in your playbook.