需通过WSL2部署Ansible:一、启用WSL2并安装Ubuntu;二、在WSL中安装Python3、pip及Ansible;三、验证安装并配置本地inventory;四、在Windows目标启用WinRM,WSL中安装pywinrm并配置连接;五、用Galaxy安装Windows专用角色如geerlingguy.iis。

如果您希望在Windows系统上使用Ansible进行自动化运维管理,但原生Windows不支持Ansible直接运行,则需借助WSL(Windows Subsystem for Linux)环境部署。以下是具体安装步骤:
一、启用并安装WSL2
WSL2提供完整的Linux内核兼容层,是运行Ansible的必要基础环境。需先确保系统满足要求并启用虚拟机平台功能。
1、以管理员身份打开PowerShell,执行:wsl --install
2、若命令不可用,手动启用:依次执行 dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart 和 dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
3、重启计算机后,运行 wsl --set-default-version 2 设为默认版本
4、从Microsoft Store安装Ubuntu(推荐22.04 LTS)
二、在WSL中安装Ansible
Ansible依赖Python及pip工具,需在WSL发行版中完成Python环境配置与Ansible包安装。
1、启动Ubuntu终端,更新软件包索引:sudo apt update
2、升级已安装软件:sudo apt upgrade -y
3、安装Python3和pip:sudo apt install python3 python3-pip python3-venv -y
4、升级pip至最新版本:python3 -m pip install --upgrade pip
5、使用pip安装Ansible:python3 -m pip install ansible
三、验证Ansible安装并配置基础环境
安装完成后需确认Ansible可执行且能识别本地主机,同时建立最小化配置以支持后续Windows目标管理。
1、检查Ansible版本:ansible --version
2、创建Ansible配置目录:mkdir -p ~/ansible/{inventory,playbooks}
Windows 命令行编码与兼容规范。涵盖 GBK/UTF-8 编码、PowerShell/pwsh 互操作、Python/Node.js、Git 配置及代码生成规则。适用于 Windows 10/11 + MSYS2/Git Bash 环境下的所有命令行操作。
3、生成简易inventory文件:echo "[local]" > ~/ansible/inventory/hosts && echo "127.0.0.1 ansible_connection=local" >> ~/ansible/inventory/hosts
4、测试连通性:ansible local -i ~/ansible/inventory/hosts -m ping
四、配置Ansible连接Windows目标主机
若需通过WSL中的Ansible管理远程Windows机器,必须启用WinRM并配置认证方式,推荐使用NTLM或CredSSP协议。
1、在目标Windows主机上以管理员身份运行PowerShell,执行:Enable-PSRemoting -Force
2、配置WinRM监听器:winrm quickconfig -force
3、设置WinRM服务为自动启动:Set-Service WinRM -StartupType Automatic
4、在WSL中安装pywinrm:python3 -m pip install pywinrm
5、在inventory中添加Windows主机条目,例如:win-server ansible_host=192.168.1.100 ansible_user=Administrator ansible_password=YourPass ansible_connection=winrm ansible_winrm_transport=ntlm
五、使用Ansible Galaxy安装Windows专用模块
Ansible Galaxy提供预构建角色,可简化Windows任务如IIS部署、注册表操作等,需单独下载并启用。
1、列出可用Windows相关角色:ansible-galaxy search windows
2、安装常用角色(如IIS):ansible-galaxy install geerlingguy.iis
3、将roles路径加入Ansible配置:echo "[defaults]" > ~/.ansible.cfg && echo "roles_path = ~/ansible/roles:/usr/share/ansible/roles" >> ~/.ansible.cfg
4、在playbook中引用角色:- role: geerlingguy.iis










