Note
This module is part of the ansible.windows collection (version 2.8.0).
You might already have this collection installed if you are using the ansible package.
It is not included in ansible-core.
To check whether it is installed, run ansible-galaxy collection list.
To install it, use: ansible-galaxy collection install ansible.windows.
To use it in a playbook, specify: ansible.windows.win_file.
Synopsis
-
Creates (empty) files, updates file modification stamps of existing files, and can create or remove directories.
-
Unlike ansible.builtin.file, does not modify ownership, permissions or manipulate links.
-
For non-Windows targets, use the ansible.builtin.file module instead.
Parameters
|
Parameter |
Comments |
|---|---|
|
path aliases: dest, name path / required |
Path to the file being managed. |
|
state string |
If If If If Choices:
|
See Also
Examples
- name: Touch a file (creates if not present, updates modification time if present) ansible.windows.win_file: path: C:\Temp\foo.conf state: touch - name: Remove a file, if present ansible.windows.win_file: path: C:\Temp\foo.conf state: absent - name: Create directory structure ansible.windows.win_file: path: C:\Temp\folder\subfolder state: directory - name: Remove directory structure ansible.windows.win_file: path: C:\Temp state: absent
Collection links
- Issue Tracker
- Repository (Sources)
How to create a directory in 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 create a directory
ansible.windows.win_fileCreates, touches, or removes files or directories
Today we’re talking about the Ansible module win_file.
The full name is ansible.windows.win_file, which means that is part of the collection of modules to interact with windows machines.
It’s a module pretty stable and out for years.
It creates, touches, or removes files or directories.
For Linux targets, use the ansible.builtin.file module instead
Main Parameters
pathpath — file pathstatestring —file/absent/directory/touch
This module has some parameters to perform different tasks.
The only required is “path”, where you specify the filesystem path of the file you’re going to edit.
The state defines the type of object we are modifying, the default is “file” but for our use case, we need the “directory” option.
Links
- ansible.windows.win_file
Playbook
How to create an “example” directory/folder in the Desktop of the user on Windows-like systems with Ansible Playbook.
code
---
- name: win_file module demo
hosts: all
vars:
mydir: 'C:\Users\vagrant\Desktop\example'
tasks:
- name: Create a directory
ansible.windows.win_file:
path: "{{ mydir }}"
state: directory
execution
ansible-pilot $ ansible-playbook -i virtualmachines/win/inventory create\ directory/directory_create_windows.yml
PLAY [win_file module demo] ***********************************************************************
TASK [Gathering Facts] ****************************************************************************
ok: [WindowsServer]
TASK [Create a directory] *************************************************************************
changed: [WindowsServer]
PLAY RECAP ****************************************************************************************
WindowsServer : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
ansible-pilot $
idempotency
ansible-pilot $ ansible-playbook -i virtualmachines/win/inventory create\ directory/directory_create_windows.yml
PLAY [win_file module demo] ***********************************************************************
TASK [Gathering Facts] ****************************************************************************
ok: [WindowsServer]
TASK [Create a directory] *************************************************************************
ok: [WindowsServer]
PLAY RECAP ****************************************************************************************
WindowsServer : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
ansible-pilot $
before execution
after execution
code with ❤️ in GitHub
Conclusion
Now you know how to create a directory in Windows-like systems with Ansible.
Subscribe to the YouTube channel, Medium, and Website, X (formerly Twitter) to not miss the next episode of the Ansible Pilot.
Academy
Learn the Ansible automation technology with some real-life examples in my
Udemy 300+ Lessons Video Course.
My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps
Donate
Want to keep this project going? Please donate
Patreon
Buy me a Pizza
2025-04-26
win_file Module
- Key Actions
- Create Files
You can usewin_fileto create new files with or without content. - Create Directories
It allows you to create new directories, including nested ones. - Touch Files
This action updates the timestamp of an existing file, making it appear as if it was recently modified. - Remove Files
You can use this module to delete files or directories. - Copy Files
It enables copying files from one location to another. - Move Files
You can move files or directories to new locations. - Set File Attributes
Control file attributes like read-only, hidden, system, and archive. - Check File Existence
Verify if a file or directory exists.
- Create Files
- Purpose
This module is specifically designed for managing files and directories on Windows systems within Ansible playbooks.
Example Usage
- hosts: windows_servers
tasks:
- name: Create a new file
win_file:
path: C:\temp\new_file.txt
state: present
content: "This is the content of the new file."
- name: Create a directory
win_file:
path: C:\temp\new_dir
state: directory
- name: Touch an existing file
win_file:
path: C:\temp\existing_file.txt
state: touch
- name: Remove a file
win_file:
path: C:\temp\old_file.txt
state: absent
Key Arguments
- attributes
Control file attributes (e.g., ‘readonly’, ‘hidden’). - force
Overwrite existing files or directories if necessary. - content
The content to be written to the file. - state
Controls the desired state of the file or directory:present: Ensure the file or directory exists.absent: Ensure the file or directory does not exist.directory: Ensure the path is a directory.touch: Update the file’s timestamp.
- path
Specifies the full path to the file or directory.
- Version Control
Integrate file management into your version control system (like Git) for better tracking and auditing. - Consistency
Ensure consistent file and directory configurations across multiple Windows servers. - Automation
Automate file and directory management tasks, reducing manual effort and potential errors. - Idempotency
Ansible playbooks are inherently idempotent, meaning they can be run multiple times without unintended side effects. Thewin_filemodule adheres to this principle.
Common Errors and Troubleshooting for Ansible’s win_file Module
Permission Issues
- Troubleshooting
- Elevate privileges
Run the playbook with elevated privileges (e.g., usingbecome: trueand specifying the appropriate user withbecome: user). - Adjust permissions
Grant the necessary permissions (read, write, execute) to the Ansible user or the user running the playbook on the target system.
- Elevate privileges
- Cause
- The Ansible user (or the user running the playbook) lacks the necessary permissions to create, modify, or delete files/directories in the target location.
- Error
- «Access Denied»
- «Insufficient privileges»
Path Issues
- Troubleshooting
- Double-check paths
Verify the accuracy of all paths in your playbook. - Use absolute paths
Always use absolute paths (e.g.,C:\path\to\file) to avoid ambiguity.
- Double-check paths
- Cause
- Incorrectly specified file or directory path (e.g., typos, missing drive letter, incorrect separators).
- Using relative paths instead of absolute paths.
- Error
- «No such file or directory»
- «Invalid path»
State Mismatch
- Troubleshooting
- Review state
Carefully review thestateparameter (e.g.,present,absent,directory) and ensure it aligns with your desired outcome. - Check existing state
Manually verify the state of the file or directory on the target system.
- Review state
- Cause
- The
stateparameter in thewin_filemodule does not match the actual state of the file or directory on the target system.
- The
- Error
- «Desired state differs from actual state»
File Locking
- Troubleshooting
- Identify and stop conflicting processes
Determine which process is locking the file and stop it temporarily. - Use force (with caution)
If necessary, use theforceoption to overwrite existing files (but be cautious as this can lead to data loss).
- Identify and stop conflicting processes
- Cause
- The target file is currently in use by another application.
- Error
- «The process cannot access the file because it is being used by another process.»
Module-Specific Issues
- attributes
Ensure the specified file attributes are valid and supported by thewin_filemodule. - content
Ensure thecontentprovided for the file is properly formatted and encoded.
General Troubleshooting Tips
- Use debugging techniques
Utilize Ansible’s debugging features (e.g.,debugmodule) to inspect variables and intermediate results. - Test on a single host
Test your playbook on a single target host before running it against a larger group. - Check Ansible logs
Examine the Ansible logs for more specific error messages and stack traces. - Run in verbose mode
Execute your playbook with the-vflag to get more detailed output, which can help pinpoint the source of the error.
- Back up critical data before making significant changes to files or directories.
- Always test your playbooks thoroughly in a non-production environment before deploying them to production systems.
Create a File
- hosts: windows_servers
tasks:
- name: Create a new file
win_file:
path: C:\temp\new_file.txt
state: present
content: "This is the content of the new file."
Create a Directory
- hosts: windows_servers
tasks:
- name: Create a new directory
win_file:
path: C:\temp\new_dir
state: directory
Touch a File
- hosts: windows_servers
tasks:
- name: Touch an existing file
win_file:
path: C:\temp\existing_file.txt
state: touch
Remove a File
- hosts: windows_servers
tasks:
- name: Remove a file
win_file:
path: C:\temp\old_file.txt
state: absent
Set File Attributes
- hosts: windows_servers
tasks:
- name: Set file attributes to read-only
win_file:
path: C:\temp\important_file.txt
state: present
attributes: readonly
- Testing
Thoroughly test your playbooks in a non-production environment before deploying them to production systems. - Error Handling
Implement error handling mechanisms (e.g.,ignore_errors) to gracefully handle potential issues. - become
If necessary, use thebecomeparameter to execute the tasks with elevated privileges (e.g.,become: true,become: user). - hosts
Replacewindows_serverswith the actual inventory group of your Windows target machines.
PowerShell Module (win_powershell)
- Example (Creating a file)
- Concept
Leverage the power of PowerShell for more complex file and directory operations.
- hosts: windows_servers
tasks:
- name: Create a file with PowerShell
win_powershell:
script: |
New-Item -Path "C:\temp\new_file.txt" -Force -Type File
Set-Content -Path "C:\temp\new_file.txt" -Value "This is the content."
- Considerations
- Requires familiarity with PowerShell scripting.
- Might be slightly more complex for basic operations compared to
win_file.
- Benefits
- Offers greater flexibility for intricate file and directory management tasks.
- Can utilize the full range of PowerShell cmdlets for advanced operations.
Template Module (template)
- Example (Creating a configuration file)
- Concept
Create and manage files using Jinja2 templating.
- hosts: windows_servers
tasks:
- name: Create a configuration file
template:
src: templates/my_config.j2
dest: C:\temp\my_config.ini
vars:
server_ip: "192.168.1.100"
port: 8080
- Considerations
- Requires understanding of Jinja2 templating syntax.
- Benefits
- Ideal for creating and managing configuration files with dynamic content.
- Provides excellent maintainability and reusability for templates.
File Transfer (copy)
- Example (Copying a file)
- Concept
Transfer files from a local or remote source to the target machine.
- hosts: windows_servers
tasks:
- name: Copy a file to the remote system
copy:
src: local_file.txt
dest: C:\temp\
- Benefits
- Simple and efficient for transferring files.
- Can be used in conjunction with other modules to manage files on the target system.
- copy
Efficient for transferring files from a local or remote source. - template
Excellent for creating and managing configuration files with dynamic content. - win_powershell
Ideal for complex operations, scripting, and leveraging PowerShell’s extensive capabilities. - win_file
Best suited for basic file and directory management operations (create, delete, touch, set attributes).
- Which module will you use to create a directory in Ansible?
- What is Win_file?
- What is file module in Ansible?
- What is register in Ansible?
- What is use of Ask_pass module in Ansible?
- What is Cowsay in Ansible?
- How do I create an Ansible multiple file?
- How do I write Ansible Yaml file?
- What is Ansible playbook?
- How do I copy multiple files in Ansible?
Which module will you use to create a directory in Ansible?
Directory can be created using file module only, as directory is nothing but a file.
What is Win_file?
win_file module – Creates, touches or removes files or directories. Note. This module is part of the ansible. windows collection (version 1.10.
What is file module in Ansible?
One practical module in Ansible is the file module. This module is responsible for performing tasks such as creating files and directories, deleting files and directories, creating soft and hard symbolic links, adding and modifying file and directory permissions, and more.
What is register in Ansible?
Ansible register is a way to capture the output from task execution and store it in a variable. This is an important feature, as this output is different for each remote host, and the basis on that we can use conditions loops to do some other tasks. Also, each register value is valid throughout the playbook execution.
What is use of Ask_pass module in Ansible?
Ask_pass is the control module in an Ansible playbook. This controls the prompting of the password when the playbook is getting executed. By default, it’s always set to True. If you are using SSH keys for authentication purposes then you really don’t have to change this setting at all.
What is Cowsay in Ansible?
Cowsay in Ansible is used to generate ASCII pictures of a cow with a message. It is enabled in Ansible by default and you can disable this kind of output by setting ANSIBLE_NOCOWS = 1. There are other ASCII drawings available apart from the cow, to use these drawings randomly, set ANSIBLE_COW_SELECTION=random.
How do I create an Ansible multiple file?
Creating Multiple Files
You can create multiple files by using a single task in an Ansible playbook. In the configuration file above, we defined: path : The » item » value means that Ansible will create a separate path for each respective file. By default, these files go in the Home folder of the remote host.
How do I write Ansible Yaml file?
To construct an Ansible playbook, start a YAML sequence that names the play, and then lists (in a sequence) one or more tasks. In each task, one or more modules may be invoked. Pay close attention to indentation by understanding the type of data you’re entering into your YAML file.
What is Ansible playbook?
Ansible playbooks are lists of tasks that automatically execute against hosts. Groups of hosts form your Ansible inventory. Each module within an Ansible playbook performs a specific task. Each module contains metadata that determines when and where a task is executed, as well as which user executes it.
How do I copy multiple files in Ansible?
find: paths: /path/to/files/ # … the rest of the task register: list1 — name: Find more files you want to move ansible. builtin. find: paths: /different/path/ # … the rest of the task register: list2 — name: Copy the files ansible.
=====================================================
Introduction
Ansible is a powerful automation tool that allows you to manage and configure your infrastructure, including creating directories and files. In this article, we will explore how to create a directory using Ansible, specifically on a Debian-based system.
Prerequisites
Before we dive into the steps, make sure you have the following:
- Ansible installed on your machine
- A Debian-based system (e.g., Ubuntu, Debian) to test the playbook
- Basic knowledge of Ansible and YAML syntax
Step 1: Create a New Ansible Playbook
To create a new Ansible playbook, navigate to the directory where you want to store your playbook and run the following command:
ansible-galaxy init my_playbook
This will create a new directory called my_playbook with the basic structure for an Ansible playbook.
Step 2: Define the Hosts and Tasks
In the hosts file, add the IP address or hostname of the Debian-based system you want to target:
[debian]
192.168.1.100
In the tasks/main.yml file, add the following code to create a new directory:
---
- name: Create a new directory
become: yes
become_method: sudo
hosts: debian
tasks:
- name: Create the www directory
file:
path: /srv/www
state: directory
mode: '0755'
Let’s break down the code:
become: yesandbecome_method: sudoallow the playbook to run with elevated privileges.hosts: debianspecifies the group of hosts to target.tasksis a list of tasks to execute on the target hosts.fileis a module that creates a new file or directory.pathspecifies the path to create the directory.state: directoryensures the directory is created.mode: '0755'sets the permissions for the directory.
Step 3: Run the Playbook
To run the playbook, navigate to the my_playbook directory and execute the following command:
ansible-playbook -i hosts playbook.yml
This will execute the playbook on the target host and create the /srv/www directory.
Step 4: Verify the Directory
To verify that the directory was created successfully, you can use the ls command on the target host:
ssh 192.168.1.100 "ls /srv"
This should output the following:
www
The /srv/www directory has been successfully created.
Conclusion
In this article, we explored how to create a directory using Ansible on a Debian-based system. We created a new Ansible playbook, defined the hosts and tasks, and ran the playbook to create the directory. With Ansible, you can automate the creation of directories and files on your infrastructure, making it easier to manage and configure your systems.
Additional Tips and Variations
- To create a directory with a specific owner and group, use the
ownerandgroupparameters in thefilemodule. - To create a directory with a specific mode, use the
modeparameter in thefilemodule. - To create a directory recursively, use the
recurseparameter in thefilemodule. - To create a directory with a specific ACL, use the
setypeparameter in thefilemodule.
Common Use Cases
- Creating a new directory for a web server
- Creating a new directory for a database
- Creating a new directory for a log file
- Creating a new directory for a configuration file
Best Practices
- Use the
becomeparameter to run the playbook with elevated privileges. - Use the
hostsparameter to specify the group of hosts to target. - Use the
tasksparameter to specify the list of tasks to execute. - Use the
filemodule to create new directories and files. - Use the
modeparameter to set the permissions for the directory.
=====================================
Introduction
In our previous article, we explored how to create a directory using Ansible on a Debian-based system. In this article, we will answer some frequently asked questions about creating directories with Ansible.
Q&A
Q: What is the difference between state: directory and state: file?
A: state: directory creates a new directory, while state: file creates a new file. If the file or directory already exists, state: directory will not overwrite it, while state: file will overwrite the existing file.
Q: How do I create a directory with a specific owner and group?
A: You can use the owner and group parameters in the file module to specify the owner and group of the directory. For example:
- name: Create the www directory
file:
path: /srv/www
state: directory
mode: '0755'
owner: www-data
group: www-data
Q: How do I create a directory with a specific mode?
A: You can use the mode parameter in the file module to specify the mode of the directory. For example:
- name: Create the www directory
file:
path: /srv/www
state: directory
mode: '0755'
Q: How do I create a directory recursively?
A: You can use the recurse parameter in the file module to create a directory recursively. For example:
- name: Create the www directory
file:
path: /srv/www
state: directory
recurse: yes
Q: How do I create a directory with a specific ACL?
A: You can use the setype parameter in the file module to create a directory with a specific ACL. For example:
- name: Create the www directory
file:
path: /srv/www
state: directory
setype: httpd_sys_content_t
Q: Can I use Ansible to create a directory on a Windows system?
A: Yes, you can use Ansible to create a directory on a Windows system. However, you will need to use the win_file module instead of the file module. For example:
- name: Create the www directory
win_file:
path: C:\srv\www
state: directory
recurse: yes
Q: Can I use Ansible to create a directory on a network file system (NFS)?
A: Yes, you can use Ansible to create a directory on an NFS. However, you will need to use the nfs module instead of the file module. For example:
- name: Create the www directory
nfs:
path: /mnt/nfs/www
state: directory
recurse: yes
Q: How do I troubleshoot issues with directory creation in Ansible?
A: You can use the debug module to troubleshoot issues with directory creation in Ansible. For example:
- name: Create the www directory
debug:
msg: "Directory {{ path }} does not exist"
when: not file.exists(path)
This will output a message if the directory does not exist.
Conclusion
In this article, we answered some frequently asked questions about creating directories with Ansible. We covered topics such as creating directories with specific owners and groups, creating directories recursively, and troubleshooting issues with directory creation. With these tips and best practices, you can use Ansible to create directories on a variety of systems, including Debian-based systems, Windows systems, and network file systems.
Additional Tips and Variations
- Use the
becomeparameter to run the playbook with elevated privileges. - Use the
hostsparameter to specify the group of hosts to target. - Use the
tasksparameter to specify the list of tasks to execute. - Use the
filemodule to create new directories and files. - Use the
modeparameter to set the permissions for the directory.
Common Use Cases
- Creating a new directory for a web server
- Creating a new directory for a database
- Creating a new directory for a log file
- Creating a new directory for a configuration file
Best Practices
- Use the
becomeparameter to run the playbook with elevated privileges. - Use the
hostsparameter to specify the group of hosts to target. - Use the
tasksparameter to specify the list of tasks to execute. - Use the
filemodule to create new directories and files. - Use the
modeparameter to set the permissions for the directory.
