Ansible 安装与使用指南
一、Ansible 核心概念
Ansible 架构
核心组件:
- 控制节点:运行Ansible的主机(Linux/Python环境)
- 被管节点:被管理的主机(无需安装Ansible)
- Inventory:主机清单文件
- Playbook:自动化任务的YAML文件
- Module:执行具体任务的单元(超过3000个内置模块)
二、控制节点安装指南(Linux)
1. 基础安装方法
# Ubuntu/Debian
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt install ansible -y
# CentOS/RHEL
sudo yum install epel-release
sudo yum install ansible -y
# 验证安装
ansible --version
2. Python虚拟环境安装(推荐)
python3 -m venv ansible-env
source ansible-env/bin/activate
pip install --upgrade pip
pip install ansible cryptography
3. macOS 安装
brew install ansible
三、被管节点准备
Linux/Unix 节点:
# 确保SSH服务运行
sudo systemctl enable sshd
sudo systemctl start sshd
# Python环境(大多数现代Linux已预装)
python3 --version
Windows 节点:
- 启用WinRM服务
- 配置防火墙允许5985/5986端口
- 执行配置脚本:
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/ansible/ansible-documentation/devel/examples/scripts/ConfigureRemotingForAnsible.ps1" -OutFile ConfigureRemotingForAnsible.ps1
.\ConfigureRemotingForAnsible.ps1
四、主机清单(Inventory)配置
基础格式 (/etc/ansible/hosts
或自定义文件)
[webservers]
web1.example.com ansible_port=2222
web2.example.com
[dbservers]
db1.example.com
db2.example.com
[cluster:children]
webservers
dbservers
[all:vars]
ansible_user=admin
ansible_ssh_private_key_file=~/.ssh/ansible_key
动态清单脚本示例(AWS)
#!/usr/bin/env python
import boto3
import json
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
inventory = {
"webservers": {
"hosts": [],
"vars": {"ansible_user": "ubuntu"}
}
}
for instance in instances:
for tag in instance.tags:
if tag['Key'] == 'Role' and tag['Value'] == 'web':
inventory['webservers']['hosts'].append(instance.public_ip_address)
print(json.dumps(inventory))
五、连接认证设置
SSH密钥认证(推荐)
# 生成密钥对
ssh-keygen -t rsa -b 4096 -f ~/.ssh/ansible_key
# 分发公钥
ssh-copy-id -i ~/.ssh/ansible_key.pub user@host
密码认证(仅测试用)
# inventory文件配置
[servers]
host1 ansible_ssh_pass=your_password
host2 ansible_ssh_pass=your_password
# 命令行指定
ansible all -i hosts -m ping -u user -k
六、Ad-Hoc命令快速开始
# 测试所有主机连通性
ansible all -m ping
# 收集主机信息
ansible webservers -m setup
# 执行Shell命令
ansible dbservers -a "free -h"
# 文件分发
ansible all -m copy -a "src=/local/path dest=/remote/path"
# 包管理
ansible ubuntu_servers -m apt -a "name=nginx state=present" --become
ansible centos_servers -m yum -a "name=nginx state=present" --become
# 服务管理
ansible webservers -m service -a "name=nginx state=restarted enabled=yes" --become
七、Playbook 核心语法
Playbook结构示例
---
- name: Configure Web Server
hosts: webservers
become: yes
vars:
http_port: 8080
max_clients: 200
tasks:
- name: Install Nginx
apt:
name: nginx
state: latest
update_cache: yes
when: ansible_os_family == 'Debian'
- name: Copy Nginx config
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
notify: Restart Nginx
handlers:
- name: Restart Nginx
service:
name: nginx
state: restarted
关键元素解析:
- hosts: 目标主机组
- become: 特权升级
- vars: 定义变量
- tasks: 任务列表
- handlers: 触发操作
- templates: Jinja2模板文件(.j2后缀)
八、常用模块详解
1. 文件管理
- name: Create directory
file:
path: /data/web
state: directory
owner: www-data
group: www-data
mode: '0755'
- name: Download file
get_url:
url: https://example.com/file.tar.gz
dest: /tmp/file.tar.gz
checksum: sha256:abcd1234...
2. 包管理
# Ubuntu/Debian
- apt:
name:
- nginx
- postgresql-client
state: latest
update_cache: yes
# CentOS/RHEL
- yum:
name: httpd
state: present
# Python包
- pip:
name:
- django
- requests
executable: pip3
3. 用户管理
- name: Create user
user:
name: deploy
comment: "Deployment User"
groups: www-data
append: yes
shell: /bin/bash
ssh_key: "{{ lookup('file', '/home/user/.ssh/id_rsa.pub') }}"
4. 服务管理
- name: Enable and start service
systemd:
name: nginx
enabled: yes
state: started
daemon_reload: yes
九、进阶技巧
1. 角色(Roles)组织
site.yml
roles/
common/
tasks/
handlers/
files/
templates/
vars/
defaults/
meta/
webserver/
...
2. 变量优先级
3. Vault加密敏感数据
# 创建加密文件
ansible-vault create secrets.yml
# 编辑加密文件
ansible-vault edit secrets.yml
# 运行Playbook使用加密数据
ansible-playbook site.yml --ask-vault-pass
4. 条件执行
tasks:
- name: Shutdown Debian systems
command: /sbin/shutdown -t now
when: ansible_facts['os_family'] == "Debian"
十、企业级最佳实践
1. CI/CD集成
# GitLab CI 示例
deploy_production:
stage: deploy
script:
- mkdir -p ~/.ssh
- echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
- ansible-playbook -i production site.yml
only:
- master
2. 性能优化
# ansible.cfg
[defaults]
forks = 50
host_key_checking = False
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_facts
fact_caching_timeout = 86400
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
pipelining = True
3. 测试框架
# 安装测试工具
pip install molecule docker
# 创建测试场景
molecule init scenario -d docker
# 运行测试
molecule test
十一、排错指南
常见问题解决:
# 增加详细输出
ansible-playbook playbook.yml -vvv
# 检查主机连接
ansible -m ping all
# 语法检查
ansible-playbook --syntax-check playbook.yml
# 测试运行(dry-run)
ansible-playbook -C playbook.yml
# 查看可用模块
ansible-doc -l
ansible-doc yum
错误处理示例:
- name: Handle task failure
block:
- name: Critical task
command: /bin/false
rescue:
- name: Rollback action
debug:
msg: "Task failed, performing rollback"
always:
- name: Always execute
debug:
msg: "Cleanup operations"
十二、Windows管理示例
Playbook示例:
- name: Configure Windows Server
hosts: windows_servers
vars:
ansible_connection: winrm
ansible_winrm_transport: ntlm
ansible_winrm_server_cert_validation: ignore
tasks:
- name: Install IIS
win_feature:
name: Web-Server
state: present
include_management_tools: yes
- name: Create website
win_iis_website:
name: TestSite
state: started
port: 8080
physical_path: C:\sites\test
学习资源推荐
- 官方文档:https://docs.ansible.com
- Ansible Galaxy:https://galaxy.ansible.com
- 最佳实践指南:https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html
- 官方培训:Red Hat Ansible Automation Platform
提示:生产环境建议使用 AWX (开源) / Ansible Automation Platform (企业版) 作为控制中心,提供API接口、RBAC权限控制和可视化任务调度。