在 Windows 上使用 WSL(Windows Subsystem for Linux) 安裝 Ansible 是目前最推薦的方式,因為 Ansible 本身是為 Linux 環境設計的,不支持原生 Windows 作為控制節點。
下面是一個 詳細步驟指南 ,幫助你在 Windows 上通過 WSL 成功安裝和配置 Ansible:
第一步:啟用 WSL
1. 打開 PowerShell(以管理員身份運行)
wsl --install
此命令會自動安裝默認的 Linux 發行版(通常是 Ubuntu),并啟用 WSL 功能。
如果你已經安裝了 WSL,可以升級到最新版本:
wsl --update
第二步:安裝 Linux 子系統(推薦使用 Ubuntu)
如果你沒有默認安裝 Ubuntu,可以通過以下命令查看可用發行版:
wsl --list --online
選擇一個你喜歡的發行版安裝,這一步可能需要科學上網,例如:
wsl --install -d Ubuntu
安裝完成后,你會被提示創建一個用戶名和密碼,這是你的 Linux 用戶賬戶。
🔧 第三步:更新系統并安裝 Python 和 pip
啟動 Ubuntu(或你安裝的其他發行版),然后執行以下命令:
sudo apt update && sudo apt upgrade -y
安裝必要的依賴:
sudo apt install python3 python3-pip git sshpass -y
python3
:Ansible 運行所需python3-pip
:用于安裝 Ansiblegit
:可選,用于從 GitHub 獲取項目sshpass
:用于支持密碼登錄(如果需要)
第四步:安裝 Ansible
安裝 Ansible:
sudo apt install ansible
第五步:驗證安裝
檢查 Ansible 是否安裝成功:
ansible --version
你應該看到類似如下輸出:
ansible [core 2.15.3]config file = Noneconfigured module search path = ['/home/youruser/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']ansible python module location = /home/youruser/.local/lib/python3.10/site-packages/ansibleexecutable location = /home/youruser/.local/bin/ansiblepython version = 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0]
?第六步:配置 Ansible(可選)
你可以創建一個簡單的 Ansible 工作目錄結構:
mkdir ~/ansible-projectcd ~/ansible-projectnano inventory.ini
示例 inventory.ini
內容:
[webservers]192.168.1.10192.168.1.11[dbservers]192.168.1.20
測試連接:
ansible all -m ping -i inventory.ini
如果目標主機 SSH 配置正確,你會看到類似輸出:
192.168.1.10 | SUCCESS => {"changed": false,"ping": "pong"}
🔐 使用 SSH 密鑰認證(推薦)
建議使用 SSH 密鑰進行免密登錄,避免每次輸入密碼。
在 WSL 中生成 SSH 密鑰:
ssh-keygen -t rsa -b 4096
將公鑰復制到目標主機:
ssh-copy-id user@目標IP
確保你的 inventory.ini
不包含明文密碼:
[webservers]web01 ansible_host=192.168.1.10 ansible_user=youruser
🛠? 常見問題解決
? 報錯:Failed to connect to the host via ssh: ... Bad configuration option: permitrootlogin
說明你在 /etc/ssh/ssh_config
文件中錯誤地添加了 PermitRootLogin
。請刪除該行。
? 報錯:to use the 'ssh' connection type with passwords, you must install the sshpass program
請安裝:
sudo apt install sshpass -y
📝 總結
步驟 | 操作 |
---|---|
啟用 WSL |
|
安裝 Ubuntu |
|
更新系統 |
|
安裝依賴 |
|
安裝 Ansible | sudo apt install ansible |
驗證 |
|
創建 inventory |
|
測試連接 |
|