Ansible 管理 Windows Server(WinRM)
Ansible 管理 Windows Server(WinRM)
Ansible 默认靠 SSH 管理 Linux,管 Windows 走的是 WinRM。一头是被管的 Windows(要装并开启 WinRM 监听器),另一头是控制机 Linux(装 Ansible + pywinrm)。这篇按"先配 Windows、再配控制机、跑通连接"的顺序记一遍。
官方文档:Windows Setup
Windows 侧:开启 WinRM
主机要求
- 支持微软当前及扩展支持周期内的 Windows 版本,桌面端 8.1 / 10,服务器端 2012、2012 R2、2016、2019、2022 都行。
- 需要 PowerShell 3.0 以上和 .NET 4.0 以上。
- 要创建并激活一个 WinRM 监听器。
WinRM 服务有两个关键部分:listener(监听哪些端口)和 service(认证等配置)。
内存补丁(PowerShell 3.0 才需要)
PowerShell 3.0 有个 bug 会限制 WinRM 服务可用内存,不打补丁 Ansible 在 Windows 上跑某些命令会失败。微软的补丁是 KB2842230,社区有现成脚本 Install-WMF3Hotfix.ps1(见 jborean93/ansible-windows)会自动检测版本、下载并静默安装。PowerShell 3.0 以上跳过这一步。
$file = "$env:temp\Install-WMF3Hotfix.ps1"
powershell.exe -ExecutionPolicy ByPass -File $file -Verbose
配置 WinRM 监听器
Ansible 官方提供 ConfigureRemotingForAnsible.ps1,会检查当前 WinRM(PS Remoting)配置并做必要修改,让 Ansible 能连上、认证、执行命令。这个脚本会:启动 WinRM 服务、启用 PS Remoting、设置 LocalAccountTokenFilterPolicy、生成自签名证书并建 HTTPS(5986)监听器、配置防火墙规则。
脚本默认用自签名证书,只适合开发/评估环境。生产环境应换成 CA 签发的证书,并用 Kerberos 等安全认证。
下载脚本放到 %temp%,管理员身份运行:
$file = "$env:temp\ConfigureRemotingForAnsible.ps1"
powershell.exe -ExecutionPolicy ByPass -File $file
查看当前监听器:
winrm enumerate winrm/config/Listener
控制机侧:安装 Ansible
Debian/Ubuntu:
sudo apt install ansible -y
sudo apt install python3-pip -y
sudo pip install pywinrm
CentOS:
yum install epel-release -y
yum install python3 -y
python3 -m pip install --upgrade pip setuptools wheel -i https://mirrors.aliyun.com/pypi/simple/
ln -s /usr/bin/pip3 /usr/bin/pip
pip install pywinrm
pip install ansible
pywinrm 是 Ansible 通过 WinRM 连 Windows 的依赖,别漏装。
写 inventory
新建一个 inventory 文件(下例叫 win_host):
[windows]
<目标主机 IP>
[windows:vars]
ansible_user="administrator"
ansible_password=""
ansible_port=5985
ansible_connection=winrm
ansible_winrm_transport=ntlm
ansible_winrm_server_cert_validation=ignore
ansible_password 这里留空只是占位——别把明文密码提交进版本库,后面用 vault 加密。ansible_winrm_server_cert_validation=ignore 配合自签名证书使用。
验证 inventory 解析:
ansible-inventory -i win_host --list
跑通连接
用 win_ping 模块探活:
ansible windows -i win_host -m win_ping
返回 pong 就说明 WinRM 链路通了。
一个最小 playbook
- name: Manage Windows servers
hosts: windows
tasks:
- name: Create directory structure
ansible.windows.win_file:
path: c:\Temp
state: directory
- name: Touch a file(Create if not present, updates modification time if present)
ansible.windows.win_file:
path: C:\Temp\foo.conf
state: touch
- name: Create a file from a Jinja2 template
ansible.windows.win_template:
src: file.conf.j2
dest: c:\Temp\file.conf
- win_stat:
path: c:\Temp\file.conf
get_checksum: yes
checksum_algorithm: md5
register: md5_checksum
- debug:
var: md5_checksum.stat.checksum
运行:
ansible-playbook -i win_host windows.yaml
常用 Windows 模块见官方 ansible.windows 集合。
用 ansible-vault 隐藏密码
别把密码明文写进 inventory。ansible-vault encrypt_string 把单个值加密成可以直接贴进 YAML 的密文:
ansible-vault encrypt_string 'Password' --name ansible_password
把输出的密文块替换 inventory 里的 ansible_password,运行 playbook 时用 --ask-vault-pass(或配置 vault 密码文件)解密。