Ansible是基于SSH协议的无Agent自动化运维工具,通过YAML格式的Playbook描述配置任务,实现批量主机管理、应用部署和滚动更新。相比Puppet和Chef,Ansible无需在目标主机安装客户端,部署门槛低,是Linux系统管理和服务器运维场景中广泛使用的配置管理工具。
Ansible架构与Inventory主机清单配置
Ansible的核心组件包括Inventory(主机清单)、Playbook(任务剧本)、Module(功能模块)和Role(角色复用)。控制节点通过SSH连接目标主机,将模块代码推送至远程执行后删除,整个过程无驻留进程。
Inventory文件定义被管理主机的分组和连接参数。以下是一个生产环境的Inventory配置示例:
# /etc/ansible/hosts
[webservers]
web01 ansible_host=192.168.1.10 ansible_user=deploy ansible_port=22
web02 ansible_host=192.168.1.11 ansible_user=deploy ansible_port=22
web03 ansible_host=192.168.1.12 ansible_user=deploy ansible_port=22
[dbservers]
db01 ansible_host=192.168.1.20 ansible_user=postgres ansible_port=2222
[loadbalancers]
lb01 ansible_host=192.168.1.1 ansible_user=admin
[webservers:vars]
ansible_python_interpreter=/usr/bin/python3
nginx_version=1.25.3
[production:children]
webservers
dbservers
loadbalancers
[production:vars]
env=prod
datacenter=dc1
使用SSH密钥认证时,通过ansible_ssh_private_key_file指定密钥路径。如果主机较多,也可以使用动态Inventory脚本从云平台API(如AWS、阿里云)动态获取主机列表。
Playbook编写与核心模块使用
Playbook是Ansible的核心,以YAML描述任务序列。以下是一个完整的Nginx部署Playbook,涵盖软件安装、配置文件分发、服务管理和健康检查:
---
- name: Deploy Nginx web server cluster
hosts: webservers
become: yes
vars:
nginx_worker_processes: auto
nginx_worker_connections: 10240
upstream_servers:
- { name: "backend1", ip: "192.168.1.20", port: 8080 }
- { name: "backend2", ip: "192.168.1.21", port: 8080 }
tasks:
- name: Install Nginx package
apt:
name: "nginx={{ nginx_version }}"
state: present
update_cache: yes
- name: Create nginx config directory
file:
path: /etc/nginx/conf.d
state: directory
owner: root
group: root
mode: '0755'
- name: Deploy nginx.conf from template
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
validate: 'nginx -t -c %s'
notify: reload nginx
- name: Deploy upstream config
template:
src: upstream.conf.j2
dest: /etc/nginx/conf.d/upstream.conf
notify: reload nginx
- name: Ensure Nginx is running and enabled
systemd:
name: nginx
state: started
enabled: yes
daemon_reload: yes
- name: Wait for Nginx to be ready
wait_for:
port: 80
timeout: 10
- name: Health check
uri:
url: "http://{{ inventory_hostname }}/"
status_code: 200
retries: 3
delay: 2
handlers:
- name: reload nginx
systemd:
name: nginx
state: reloaded
其中template模块使用Jinja2模板引擎,nginx.conf.j2中的变量引用示例如下:
# nginx.conf.j2
worker_processes {{ nginx_worker_processes }};
events {
worker_connections {{ nginx_worker_connections }};
}
http {
upstream backend {
{% for server in upstream_servers %}
server {{ server.ip }}:{{ server.port }} weight=3 max_fails=3 fail_timeout=30s;
{% endfor %}
}
server {
listen 80;
server_name _;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_connect_timeout 5s;
proxy_read_timeout 30s;
}
}
}
Roles角色复用与目录结构规范
当Playbook规模增长时,使用Role将任务、变量、模板、文件按功能模块化组织。Ansible Galaxy社区提供了大量现成Role。标准的Role目录结构如下:
roles/
└── nginx/
├── tasks/
│ ├── main.yml
│ ├── install.yml
│ └── configure.yml
├── handlers/
│ └── main.yml
├── templates/
│ ├── nginx.conf.j2
│ └── upstream.conf.j2
├── vars/
│ └── main.yml
├── defaults/
│ └── main.yml
├── files/
│ └── index.html
└── meta/
└── main.yml
在Playbook中引用Role:
---
- name: Full stack deployment
hosts: production
become: yes
roles:
- role: nginx
vars:
nginx_worker_connections: 20480
- role: mysql
when: "'dbservers' in group_names"
- role: monitoring
tags: [monitoring, always]
批量滚动更新与错误处理策略
生产环境中滚动更新(Rolling Update)是避免服务中断的关键。通过serial参数控制每次操作的主机比例,结合失败阈值实现灰度发布:
---
- name: Rolling update application
hosts: webservers
become: yes
serial: "30%"
max_fail_percentage: 20
tasks:
- name: Drain node from load balancer
command: /usr/local/bin/lb_drain.sh {{ inventory_hostname }}
- name: Pull latest image
command: docker pull app:{{ version }}
- name: Restart container
systemd:
name: app
state: restarted
- name: Wait for app health
uri:
url: "http://{{ inventory_hostname }}:8080/health"
status_code: 200
retries: 5
delay: 3
- name: Add node back to load balancer
command: /usr/local/bin/lb_add.sh {{ inventory_hostname }}
Ansible的幂等性(Idempotency)设计保证了重复执行Playbook不会产生副作用——每个模块在执行前会检查目标状态是否已达预期,仅在需要变更时才执行操作。这一特性使得Ansible非常适合用于持续配置管理和服务器的安全加固场景。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/ansible-zi-dong-hua-yun-wei-shi-zhan-playbook-bian-xie-yu/