Ansible Pilot

Check if a directory exists - Ansible module stat

Deep dive into the Ansible module stat of the collection ansible.builtin to test if a specified path is a directory and print a message. Live demo and Ansible playbook included.

How to check if a directory exists in Ansible?

I’m going to show you a live demo 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 module instead.

Main parameters and return values

The only mandatory parameter is “path” which is the filesystem full path of the object to check.

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.


Let’s jump in a real-life playbook to check if a directory exists with Ansible.


- name: check if the directory exists
  hosts: all
  become: false
    directory: "/tmp"
    - name: Check if the directory exists
        path: "{{ directory }}"
      register: dir_to_check

    - name: Directory found
        msg: "Directory {{ directory }} present"
      when: dir_to_check.stat.isdir is defined and dir_to_check.stat.isdir

code with ❤️ in GitHub


Now you know better the Ansible module stat and you could use it successfully in your playbook. Subscribe to the YouTube channel, Medium, Website and Twitter to not miss the next episode of the Ansible Pilot.


Learn the Ansible automation technology with some real-life examples in my

My book Ansible By Examples: 100+ Automation Examples For Linux and Windows System Administrator and DevOps

Want to keep this project going? Please donate

Follow me

Subscribe not to miss any new releases

July 29, 2021

FREE Top 10 Best Practices

Top 10 Best Practices of Ansible Automation: save time, reduce errors and stress