第二章:安装与配置

掌握 Ansible 的多种安装方式和基础配置方法。

最后更新: 2024-01-16
页面目录

Ansible 安装与配置

本章节详细介绍 Ansible 的各种安装方式以及配置文件的使用方法。

安装方式概述

安装方式 适用场景 优点 缺点
pip 通用 最新版本、灵活 需要 Python 环境
yum/dnf RHEL/CentOS 系统包管理 版本可能较旧
apt Debian/Ubuntu 系统包管理 版本可能较旧
源码 高级用户 定制化 维护复杂

使用 pip 安装

pip 是最推荐的安装方式,可以获取最新版本的 Ansible。

安装最新版

# 安装最新版 Ansible
pip install ansible

# 安装指定版本
pip install ansible==2.9.27

# 升级 Ansible
pip install --upgrade ansible

使用虚拟环境

# 创建虚拟环境
python3 -m venv ansible-venv

# 激活虚拟环境
source ansible-venv/bin/activate

# 安装 Ansible
pip install ansible

# 退出虚拟环境
deactivate

安装 Ansible Core

# Ansible 2.10+ 版本拆分,core 版本更精简
pip install ansible-core==2.14.0

使用系统包管理器安装

RHEL/CentOS/Rocky Linux

# EPEL 仓库
yum install epel-release

# 安装 Ansible
yum install ansible

# 验证安装
ansible --version

Debian/Ubuntu

# 添加 PPA 仓库(Ubuntu)
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository --yes --update ppa:ansible/ansible

# 安装 Ansible
sudo apt install ansible

# 验证安装
ansible --version

macOS

# 使用 Homebrew
brew install ansible

# 验证安装
ansible --version

验证安装

# 检查 Ansible 版本
ansible --version

# 输出示例
ansible 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.9/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.9.10

Ansible 配置文件

Ansible 使用 ansible.cfg 配置文件来控制其行为。

配置文件优先级

1. ANSIBLE_CONFIG 环境变量指定的路径
2. ./ansible.cfg(当前目录)
3. ~/.ansible.cfg(用户主目录)
4. /etc/ansible/ansible.cfg(系统默认)

配置文件结构

[defaults]
# 基本配置
inventory      = ./inventory
library        = ./library
module_utils   = ./module_utils
remote_tmp     = ~/.ansible/tmp
pattern        = *
forks          = 5
poll_interval  = 15
sudo_user      = root
ask_sudo_pass  = False
ask_pass       = False
transport      = smart
remote_port    = 22
module_lang    = C
gathering = explicit
host_key_checking = False
timeout = 10
log_path = /var/log/ansible.log

[privilege_escalation]
become=True
become_method=sudo
become_user=root
become_ask_pass=False

[ssh_connection]
# SSH 连接配置
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no
pipelining = True
control_path = /tmp/ansible-ssh-%%h-%%p-%%r

创建项目配置文件

1. 创建项目目录结构

# 创建项目目录
mkdir -p ~/ansible-project
cd ~/ansible-project

# 创建基础目录
mkdir -p inventory group_vars host_vars roles library plugins

2. 创建 ansible.cfg

# ansible.cfg
[defaults]
inventory = inventory
roles_path = roles
host_key_checking = False
timeout = 30

[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

3. 创建基础 Inventory 文件

# inventory/hosts
# 单主机
[webserver]
192.168.1.10 ansible_user=root ansible_ssh_private_key_file=~/.ssh/id_rsa

# 主机组
[webservers]
web01 ansible_host=192.168.1.10
web02 ansible_host=192.168.1.11
web03 ansible_host=192.168.1.12

# 数据库组
[dbservers]
db01 ansible_host=192.168.2.10
db02 ansible_host=192.168.2.11

# 组变量
[webservers:vars]
nginx_version=1.24.0
app_port=8080

# 父组和子组
[production:children]
webservers
dbservers

[production:vars]
environment=production

SSH 无密码登录配置

1. 生成 SSH 密钥

# 生成 SSH 密钥对
ssh-keygen -t rsa -b 4096 -C "ansible@your-email.com" -f ~/.ssh/ansible_rsa

# 一键生成(无交互)
ssh-keygen -t rsa -b 4096 -N "" -f ~/.ssh/id_rsa

2. 配置 SSH 密钥登录

# 方式一:使用 ssh-copy-id
ssh-copy-id -i ~/.ssh/id_rsa.pub user@192.168.1.10

# 方式二:手动复制公钥
cat ~/.ssh/id_rsa.pub | ssh user@192.168.1.10 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# 方式三:使用 Ansible 分发公钥
ansible all -i inventory -m authorized_key -a "user=root key='{{ lookup('file', '~/.ssh/id_rsa.pub') }}'"

3. SSH 配置优化

# ~/.ssh/config
Host *
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
    IdentityFile ~/.ssh/id_rsa
    ConnectTimeout 10
    ServerAliveInterval 60
    ServerAliveCountMax 3

Host 192.168.1.*
    User root
    Port 22

Ansible 命令行工具

核心命令

命令 说明
ansible 在指定主机上执行单个任务
ansible-playbook 执行 Playbook
ansible-doc 查看模块文档
ansible-galaxy 管理 Galaxy 角色
ansible-vault 加密敏感数据
ansible-config 查看/编辑配置
ansible-inventory 查看 Inventory 信息
ansible-pull 客户端拉取模式

常用选项

# 查看帮助
ansible --help

# 常用选项
ansible <pattern> -m <module> -a <args> [options]

# 示例
ansible all -m ping                          # ping 所有主机
ansible webserver -m command -a "uptime"    # 在 webserver 组执行命令
ansible all -m copy -a "src=./file dest=/tmp/"  # 复制文件

环境变量

变量 说明 示例
ANSIBLE_CONFIG 配置文件路径 /path/to/ansible.cfg
ANSIBLE_INVENTORY Inventory 路径 ./inventory
ANSIBLE_ROLES_PATH Roles 搜索路径 ./roles:/usr/share/ansible/roles
ANSIBLE_LIBRARY 模块搜索路径 ./library
ANSIBLE_TIMEOUT 连接超时 30

离线安装

使用 pip 离线安装

# 在有网络的环境下载包
pip download ansible ansible-core

# 将下载的文件复制到离线环境
scp *.whl user@offline-server:/tmp/

# 在离线环境安装
pip install *.whl

使用离线安装包(RHEL/CentOS)

# 创建本地仓库
mkdir -p /opt/ansible-offline
cd /opt/ansible-offline

# 使用 createrepo 创建本地仓库
yum install -y createrepo
createrepo /opt/ansible-offline

# 配置 yum 仓库
cat > /etc/yum.repos.d/ansible-local.repo << EOF
[ansible-local]
name=Ansible Local Repository
baseurl=file:///opt/ansible-offline
enabled=1
gpgcheck=0
EOF

# 安装
yum install ansible

卸载 Ansible

# pip 卸载
pip uninstall ansible

# 系统包卸载
# RHEL/CentOS
yum remove ansible

# Ubuntu/Debian
apt remove ansible

下一步

现在你已经掌握了 Ansible 的安装和配置,接下来让我们开始快速入门。

👉 快速入门