anpanman
Published on

Connect to Windows 2012 R2 with Ansible

前言

Ansible 現在也支援 Windows 了,但是要注意的是,Ansible 本身是使用 SSH 來連線的,但是 Windows 版本的 Ansible 並不支援 SSH,所以要在 Windows 主機上安裝 WinRM 服務,並且設定好防火牆,才能讓 Ansible 連線。

本地設定(Ubuntu)

安裝 Python 3.8.10

sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.8

references: https://www.knowledgehut.com/blog/data-science/install-python-on-ubuntu

安裝 pip

sudo apt install python3-pip

安裝 Ansible

sudo apt-get install software-properties-common
sudo apt-add-repository ppa:ansible/ansible
sudo apt-get update
sudo apt-get install ansible

安裝 pywinrm

Ansible 本身是使用 Python 來執行的,所以要先安裝 pywinrm。

pip install pywinrm

在本地定義目標 Windows 主機

在 /etc/ansible/hosts,定義 Windows 主機的 IP 位置,並且設定好連線的帳號與密碼。 使用 EC2 時,須注意 IP (xx.xx.xx.xx)與管理機的 IP (xx.xx.xx.xx)是否在同一個 VPC,是的話就可以直接使用內網 IP 連線,不是的話就要使用外網 IP 連線。

[windows]
xx.xx.xx.xx ansible_port=5985 ansible_connection=winrm ansible_winrm_server_cert_validation=ignore ansible_user=Administrator

[windows:vars]
ansible_user=Administrator
ansible_password=XXXXXXXXXXXXXXXXXXXXXXXX
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore
ansible_port=5985
ansible_winrm_transport=ntlm
ansible_python_interpreter=C:\Program Files\Python310\python.exe

Windows 主機設定

安裝 WinRM、.NET Framework 4.5

通常 Windows 2012 R2 都會預設安裝 WinRM 服務,但是預設是不開啟的,所以要先開啟 WinRM 服務,並且設定好防火牆。 另外,Ansible 本身是使用 Python 來執行的,所以要先安裝 .NET Framework 4.5 以上的版本。

設定防火牆

WinRM 服務預設使用 5985 port,所以要先開啟防火牆的 5985 port。 在安裝 Ansible 的主機上,執行以下指令,確認是否可以連線到 Windows 主機。

netsh advfirewall firewall add rule name="TCP Port 5985" dir=in action=allow protocol=TCP localport=5985
netsh advfirewall firewall show rule name="TCP Port 5985"

開啟 WinRM 服務

在 Windows 主機上,執行以下指令,開啟 WinRM 服務。

winrm quickconfig

安裝 python

Ansible 本身是使用 Python 來執行的,所以要先安裝 Python 3.6 以上的版本,建議安裝 Python 3.8.10 或 3.10。

測試連線

在安裝 Ansible 的主機上,執行以下指令,確認是否可以連線到 Windows 主機。

ansible windows -m win_ping