在 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 = None
configured 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/ansible
executable location = /home/youruser/.local/bin/ansible
python version = 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0]
第六步:配置 Ansible(可选)
你可以创建一个简单的 Ansible 工作目录结构:
mkdir ~/ansible-project
cd ~/ansible-project
nano inventory.ini
示例 inventory.ini
内容:
[webservers]
192.168.1.10
192.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 |
|
测试连接 |
|