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.

Ansible stat Module: Check File Properties and Existence (Complete Guide)

By Luca Berton · Published 2024-01-01 · Category: file-operations

How to use Ansible stat module to check if files exist, get file size, permissions, checksums. Complete guide with playbook examples for file validation.

Ansible stat Module: Check File Properties and Existence (Complete Guide)

The ansible.builtin.stat module retrieve file or filesystem status. This guide covers all common use cases with practical playbook examples.

Check if a File Exists

Get File Properties

Verify File Checksum

Check if Path is a Directory

Check File Age

Common stat Fields

The stat result contains these useful fields: • stat.exists — whether the path exists • stat.isdir — is it a directory • stat.isreg — is it a regular file • stat.islnk — is it a symbolic link • stat.size — file size in bytes • stat.uid / stat.gid — owner/group IDs • stat.pw_name / stat.gr_name — owner/group names • stat.mode — permissions (e.g., "0644") • stat.checksum — file checksum (when requested) • stat.mtime — last modified time (epoch) • stat.atime — last access time (epoch)

FAQ

How do I 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 idempotent way to conditionally create or modify files.

What is the difference between stat and file modules?

The stat module reads file information without changing anything. The file module creates, modifies, or deletes filesystem objects. Use stat for checks, file for changes.

How do I get a file checksum in Ansible?

Use ansible.builtin.stat with checksum_algorithm: sha256 (or md5, sha1). Access the result via result.stat.checksum.

Conclusion

The ansible.builtin.stat module is a versatile tool for retrieve file or filesystem status. Use the examples above as starting points and adapt them to your infrastructure needs.

Related ArticlesAnsible file Module: Manage Files and DirectoriesAnsible find Module: Search for Files

Category: file-operations

Browse all Ansible tutorials · AnsiblePilot Home