Ansible win_stat: Check if File or Directory Exists on Windows (Examples)
By Luca Berton · Published 2024-01-01 · Category: installation
How to check if a file or directory exists on Windows using Ansible win_stat module. Conditional tasks, file properties, checksum verification with practical examples.
How to check if a directory/folder exists on Windows-like systems with 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 on Windows-like systems • ansible.windows.win_stat • Get information about Windows files
Let's talk about the Ansible module win_stat. The full name is ansible.windows.win_stat, which means that is part of the collection of modules specialized to interact with Windows target host. It's a module pretty stable and out for years. It works in Windows and Windows Server operating systems. It gets information about Windows files. For Linux target use the ansible.builtin.stat module instead.
Parameters & Return Values
Mandatory Parameters • path string
Main Return Values • stat complex - isdir
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
Links • ansible.windows.win_stat
## Playbook
How to check if the "example" directory/folder exists on the Desktop of the user on Windows-like systems with Ansible Playbook.
code
directory doesn't exist execution
!win_stat directory doesn't exist
directory exist execution
Conclusion Now you know how to check if a directory exists on Windows-like systems with Ansible.
Check Directory Exists
Check File Exists
Get File Properties
Checksum Verification
Common Patterns
Backup before overwrite
Wait for file to appear
win_stat vs stat
| Module | Platform | Path Style | |--------|----------|------------| | win_stat | Windows | C:\path\to\file | | stat | Linux/macOS | /path/to/file |
Available Properties
| Property | Description | |----------|-------------| | exists | File/directory exists | | isdir | Is a directory | | isreg | Is a regular file | | size | File size in bytes | | checksum | File hash (with algorithm) | | isreadonly | Read-only flag | | ishidden | Hidden flag | | lastwritetime | Last modification time |
FAQ
How do I check a UNC path?
Does win_stat follow symlinks?
Yes by default. Use follow: false to check the link itself.
Related Articles • Ansible when Conditional Guide • Ansible Inventory Guide • Ansible for Windows Guide
Category: installation
Watch the video: Ansible win_stat: Check if File or Directory Exists on Windows (Examples) — Video Tutorial