AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,100 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example" published by Apress, and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

How to Check if a File Exists in Ansible (4 Methods)

By Luca Berton · Published 2024-01-01 · Category: database-automation

How to check if a file exists in Ansible using stat module, when conditional, and find module. Complete guide with playbook examples for file existence checks.

How to Check if a File Exists in Ansible (4 Methods)

Checking whether a file exists before taking action is one of the most common patterns in Ansible. Here are four methods, from simplest to most flexible.

Method 1: stat Module (Recommended)

Method 2: stat with Multiple Properties

Method 3: find Module (Multiple Files)

Method 4: creates/removes Parameters

Some modules have built-in file existence checks:

Check if Directory Exists

Check Remote vs Local File

FAQ

What is the best way to check if a file exists in Ansible?

Use ansible.builtin.stat with register, then check result.stat.exists in a when conditional. This is the standard, idempotent approach.

Can I check if a file exists on the Ansible control node?

Yes. Add delegate_to: localhost to the stat task to check files on the control node instead of the remote host.

How do I check if a file exists and is not empty?

Use stat and check both result.stat.exists and result.stat.size > 0 in your conditional.

Related ArticlesAnsible stat Module: Complete GuideAnsible find Module: Search FilesAnsible file Module: Create and Manage Files

Category: database-automation

Browse all Ansible tutorials · AnsiblePilot Home