一、Environment
Operating System | IP | Remark |
CentOS 7.4 | 172.50.1.119 | Ansible Manager |
Windows Server 2008 R2 | 172.50.1.172 | Ansible Client |
二、Let’s Start
Windows Server
- Ansible requires PowerShell version 3.0 and .NET Framework 4.0 or newer to function on older operating systems like Server 2008 and Windows 7【Windows Server 2012 就不需要升级了,2012 的PowerShell默认版本就是 4.0】,如果能访问互联网,可以通过官方脚本自动升级,否则下载离线包(.NET Framework 4.5 | PowerShell 4.0 )进行安装
- 重启Windows Server之后,打开PowerShell,查看升级是否成功,如图1所示

- 开启 winrm 服务 (以下命令都在 PowerShell 中进行)
# 1.查看powershell执行策略
get-executionpolicy
# 2.更改powershell执行策略为remotesigned【输入y确认】
set-executionpolicy remotesigned
# 3.配置winrm service并启动服务
winrm quickconfig
# 4.修改winrm配置,启用远程连接认证【这里是PowerShell的命令,如果用cmd的话,@前面的' 和 末尾的' 要去掉的】【如图2所示】
winrm set winrm/config/service/auth '@{Basic="true"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
# 5.查看winrm service启动监听状态【如果有应答,说明服务配置并启动成功了】【如图3所示】
winrm enumerate winrm/config/listener


- 设置防火墙入站规则 (允许5985端口入站通过,略)
CentOS 7
重点:千万不要 yum 安装,选择 pip 安装,或者二进制包安装。否则,即便安装了 pywinrm 插件也无法管理 Windows Server。报图4错误。

- 安装pip命令【先安装 Python3】
# 1.从官网下载pip包到本地,官网链接:https://pypi.org/project/pip/#files
[root@localhost ~]# wget https://files.pythonhosted.org/packages/8e/76/66066b7bc71817238924c7e4b448abdb17eb0c92d645769c223f9ace478f/pip-20.0.2.tar.gz
# 2.解压
[root@localhost ~]# tar -zxvf pip-20.0.2.tar.gz -C /usr/local
# 3.安装
[root@localhost ~]# cd /usr/local/pip-20.0.2
[root@localhost pip-20.0.2]# python3 setup.py install
- 安装 pywinrm 插件
[root@localhost ~]# pip install pywinrm
... ...
Successfully installed pywinrm-0.4.1
- pip 安装 ansible
[root@localhost ~]# pip install ansible
三、Configure and Test
配置文件默认路径:/etc/ansible/hosts
- 在此配置文件尾巴追加以下信息,ansible_ssh_user 是 Windows Server 的用户名,ansible_ssh_pass 是Windows Server 的密码
[windows]
172.50.1.172 ansible_ssh_user="Administrator" ansible_ssh_pass="Password" ansible_ssh_port=5985 ansible_connection="winrm" ansible_winrm_server_cert_validation=ignore
- 验证
[root@localhost ~]# ansible windows -m win_ping
172.50.1.172 | SUCCESS => {
"changed": false,
"ping": "pong"
}
四、说明
- 升级PowerShell到4.0要先升级.Net Franmwork;
- 开启 winrm 服务在 CMD 下、PowerShell 下语法是不一样的,本文是在 PowerShell 下进行的,有截图为证;
- 一定要安装pywinrm插件,否则管理Windows Server的时候会报错”msg”: “winrm or requests is not installed: No module named winrm”
- 如果安装了 pywinrm 还是报这个错,是因为 yum 安装的 ansible 无法调用 pip 安装的 pywinrm 插件,故而建议用 pip 安装 ansible 或者用源码包安装 ansible。【这个坑埋得比较深】【用yum安装ansible无法调用 pip 安装的 pywinrm 插件,不确定是不是必现,但在我工作的测试环境出现了】