如何使用 Ansible 在 Windows 系统中自动化创建目录
以下是一个完整的指南,介绍如何使用 Ansible 的 win_file 模块在 Windows 系统中创建目录。我们将创建一个名为 example 的目录,位于用户桌面上。
使用 Ansible 模块 win_file 创建目录
关于 win_file 模块
win_file 是 Ansible 的一个模块,全名为 ansible.windows.win_file,属于 Ansible 的 Windows 模块集合。它用于创建、触摸或删除文件和目录。对于 Linux 系统,应使用 ansible.builtin.file 模块。
主要参数
path(字符串,必需):指定文件或目录的路径。state(字符串,默认为file):定义要操作的对象类型。可选值包括:file:确保路径是一个文件。directory:确保路径是一个目录。absent:删除文件或目录。touch:创建一个空文件,类似于 Unix 的touch命令。
示例代码
以下是一个 Ansible Playbook,用于在 Windows 系统中创建目录。
文件名:directory_create_windows.yml
---
- name: win_file 模块示例
hosts: all
vars:
mydir: 'C:\Users\vagrant\Desktop\example' # 目标目录路径
tasks:
- name: 创建目录
ansible.windows.win_file:
path: "{{ mydir }}"
state: directory
执行命令
$ ansible-playbook -i win/inventory create\ directory/directory_create_windows.yml
执行结果
PLAY [win_file 模块示例] *******************************************************
TASK [Gathering Facts] ******************************************************
ok: [WindowsServer]
TASK [创建目录] ******************************************************
changed: [WindowsServer]
PLAY RECAP *******************************************************************
WindowsServer : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
验证目录是否创建成功
在 Windows 主机上检查目录是否已创建:
$ ssh vagrant@WindowsServer
C:\Users\vagrant\Desktop>dir
Volume in drive C is Windows
Volume Serial Number is 1234-ABCD
Directory of C:\Users\vagrant\Desktop
01/01/2024 12:00 PM <DIR> example
0 File(s) 0 bytes
1 Dir(s) 123,456,789,012 bytes free
通过以上步骤,您可以使用 Ansible 的 win_file 模块轻松在 Windows 系统中创建目录。