Ansible создать папку windows

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 directory, all immediate subdirectories will be created if they do not exist.

If file, the file will NOT be created if it does not exist, see the ansible.windows.win_copy or ansible.windows.win_template module if you want that behavior.

If absent, directories will be recursively deleted, and files will be removed.

If touch, an empty file will be created if the path does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way touch works from the command line).

Choices:

  • "absent"

  • "directory"

  • "file"

  • "touch"

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_file Creates, 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

  • path path — file path
  • state string — 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

Join 50+ hours of courses in our exclusive community

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

win_file before execution

after execution

win_file 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.

BUY the Complete Udemy 300+ Lessons Video Course

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

BUY the Complete PDF BOOK to easily Copy and Paste the 250+ Ansible code

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 use win_file to 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.
  • 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. The win_file module 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., using become: true and specifying the appropriate user with become: user).
    • Adjust permissions
      Grant the necessary permissions (read, write, execute) to the Ansible user or the user running the playbook on the target system.
  • 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.
  • 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 the state parameter (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.
  • Cause
    • The state parameter in the win_file module does not match the actual state of the file or directory on the target system.
  • 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 the force option to overwrite existing files (but be cautious as this can lead to data loss).
  • 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 the win_file module.
  • content
    Ensure the content provided for the file is properly formatted and encoded.

General Troubleshooting Tips

  • Use debugging techniques
    Utilize Ansible’s debugging features (e.g., debug module) 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 -v flag 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 the become parameter to execute the tasks with elevated privileges (e.g., become: true, become: user).
  • hosts
    Replace windows_servers with 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).


  1. Which module will you use to create a directory in Ansible?
  2. What is Win_file?
  3. What is file module in Ansible?
  4. What is register in Ansible?
  5. What is use of Ask_pass module in Ansible?
  6. What is Cowsay in Ansible?
  7. How do I create an Ansible multiple file?
  8. How do I write Ansible Yaml file?
  9. What is Ansible playbook?
  10. 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.

Ansible – Create a new directory on a CIFS shared folder

In this post, I will show you how to create a directory on a CIFS shared folder hosted on the Windows machine

This task can be achieved by configuring the WinRM listener on the Windows machine. In the playbook, we will communicate with the listener using CredSSP. The TCP port is defined on 5986 (WinRM default port for HTTPS listener)

You can find here a documentation on how to configure this WinRM listener

---
- hosts: myWindowsNode
  vars:
    ansible_user: mywinusername
    ansible_password: Password    
    ansible_port: 5986
    ansible_connection: winrm
    ansible_winrm_transport: credssp
    ansible_winrm_server_cert_validation: validate

  tasks:
  - name: create the folder called "TheNewFolder"
    win_file:
      path: "//myFileSEerver01/MySharedFolder/TheNewFolder"
      state: directory

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Программа для озвучки текста windows
  • Сколько нужно видеопамяти для windows 7
  • Команда вызова службы windows
  • Сетевой драйвер для windows 10 64 bit asus vivobook
  • Microsoft store не качает приложения windows 11