Ansible自动化介绍
Ansible是一种开源的自动化运维工具,用于配置管理、应用部署和任务自动化。其核心基于YAML语言编写的Playbook,通过SSH协议与目标节点通信,无需在被控端安装额外代理。关键组件包括:
- Inventory:定义目标主机和分组;
- Playbook:描述自动化任务的YAML文件;
- Module:执行特定任务的代码单元 (如文件操作、包管理);
环境准备与安装
在Linux控制节点或主节点上安装Ansible:
bash
# Ubuntu/Debian
sudo apt update && sudo apt install ansible
# CentOS/RHEL
sudo yum install ansible
# macOS
brew install ansible
验证安装:
bash
ansible --version
配置Inventory文件
默认Inventory文件路径为/etc/ansible/hosts,也可自定义。示例:
ini
[web_servers]
192.168.1.10 ansible_user=ubuntu
192.168.1.11 ansible_user=ubuntu
[db_servers]
db.example.com ansible_ssh_private_key_file=/path/to/key.pem
编写第一个Playbook
创建deploy_nginx.yml文件,部署Nginx:
yaml
---
- name: Install and start Nginx
hosts: web_servers
become: yes
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
when: ansible_os_family == "Debian"
- name: Start Nginx service
service:
name: nginx
state: started
enabled: yes
执行Playbook与常用命令
运行Playbook:
bash
ansible-playbook -i inventory_file deploy_nginx.yml
常用命令:
- 测试主机连通性:
ansible all -m ping - 临时执行命令:
ansible web_servers -a "uptime"
进阶功能与最佳实践
变量管理:
-
在Playbook中定义变量:
yamlvars: http_port: 80 -
使用外部变量文件(如
group_vars/web_servers.yml)。
角色(Roles) :
通过模块化组织Playbook:
bash
ansible-galaxy init roles/nginx
目录结构示例:
roles/nginx/
├── tasks/
├── handlers/
├── templates/
错误处理:
- 使用
ignore_errors: yes忽略任务失败。 - 通过
block和rescue实现异常捕获。
性能优化技巧
-
启用SSH长连接:在
ansible.cfg中设置:ini[ssh_connection] ssh_args = -o ControlMaster=auto -o ControlPersist=60s -
使用
strategy: free允许异步任务执行。
通过上述方法,Ansible可实现从简单配置到复杂部署的自动化流程,显著提升运维效率。