Ansible架构与工作原理
Ansible是DevOps实践中广泛使用的自动化运维工具,采用无代理(agentless)架构,通过SSH协议管理目标主机,无需在远程节点安装客户端。Ansible的核心优势在于声明式配置:管理员描述期望的系统状态,Ansible负责将系统调整到该状态。在SRE稳定性工程中,Ansible用于批量部署、配置漂移修复和故障应急响应,大幅减少人工操作带来的不一致性。
Inventory主机清单配置
Inventory文件定义了Ansible管理的所有主机及其分组,支持INI和YAML两种格式。
# /etc/ansible/hosts - INI格式
[webservers]
web01 ansible_host=192.168.1.10 ansible_user=deploy
web02 ansible_host=192.168.1.11 ansible_user=deploy
web03 ansible_host=192.168.1.12 ansible_user=deploy
[dbservers]
db01 ansible_host=192.168.1.20 ansible_user=postgres
[prod:children]
webservers
dbservers
[prod:vars]
ansible_python_interpreter=/usr/bin/python3
通过组嵌套和组变量实现层次化管理。ansible_host指定实际IP,ansible_user指定SSH连接用户。生产环境建议使用SSH密钥认证而非密码。
Playbook基础与YAML语法
Playbook是Ansible的核心配置文件,使用YAML格式描述任务序列。每个task调用一个模块完成特定操作。
---
# deploy_web.yml - Web服务器批量部署
- name: Deploy Nginx web servers
hosts: webservers
become: yes
vars:
nginx_version: "1.25.3"
worker_processes: auto
tasks:
- name: Install required packages
apt:
name:
- nginx
- python3-pip
- unzip
state: present
update_cache: yes
- name: Configure nginx
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
backup: yes
notify: restart nginx
- name: Ensure nginx is running and enabled
service:
name: nginx
state: started
enabled: yes
- name: Open firewall ports
ufw:
rule: allow
port: "{{ item }}"
proto: tcp
loop:
- 80
- 443
handlers:
- name: restart nginx
service:
name: nginx
state: restarted
become: yes表示以sudo权限执行任务。notify仅在task状态为changed时触发handler,避免不必要的重启。backup: yes在修改文件前自动备份原文件。
常用模块详解与实战
Ansible提供数百个内置模块,日常运维中最常用的包括:
# copy模块:复制文件到远程主机
- name: Copy config file
copy:
src: files/app.conf
dest: /etc/app/app.conf
owner: deploy
group: deploy
mode: '0644'
# file模块:管理文件和目录
- name: Create application directory
file:
path: /opt/app/logs
state: directory
recurse: yes
owner: deploy
mode: '0755'
# git模块:拉取代码仓库
- name: Deploy application code
git:
repo: https://github.com/example/app.git
dest: /opt/app/current
version: release-v2.1
force: yes
# command/shell模块:执行命令
- name: Run database migration
command: /opt/app/current/bin/migrate.sh
args:
chdir: /opt/app/current
register: migrate_result
- name: Show migration output
debug:
var: migrate_result.stdout
# stat模块:检查文件状态
- name: Check if config exists
stat:
path: /etc/app/app.conf
register: config_file
- name: Create config if missing
copy:
src: files/default.conf
dest: /etc/app/app.conf
when: not config_file.stat.exists
register关键字将模块执行结果保存到变量中,后续task可通过when条件判断决定是否执行,实现条件式配置。
Roles角色化组织与复用
当Playbook规模增大时,使用Roles将任务、变量、模板、文件按功能模块拆分,提升可维护性和复用性。Docker自动化部署场景中可将容器安装、镜像管理、服务编排封装为独立Role。
# Role目录结构
roles/
nginx/
tasks/main.yml # 主任务文件
handlers/main.yml # 触发器
templates/nginx.conf.j2 # Jinja2模板
vars/main.yml # Role变量
defaults/main.yml # 默认变量
files/ # 静态文件
meta/main.yml # Role元数据依赖
# 调用Role的Playbook
- name: Configure all servers
hosts: all
become: yes
roles:
- role: nginx
vars:
nginx_worker_connections: 1024
- role: docker
when: "'container_hosts' in group_names"
变量管理与条件渲染
Ansible变量支持多层级覆盖,优先级从高到低为:命令行-e参数 > Playbook vars > Inventory组变量 > Role defaults。Jinja2模板引擎实现动态配置文件渲染。
{# nginx.conf.j2 - Jinja2模板 #}
worker_processes {{ worker_processes | default('auto') }};
worker_connections {{ nginx_worker_connections | default(1024) }};
{% if nginx_enable_https is defined and nginx_enable_https %}
http {
server {
listen 80;
server_name {{ nginx_server_name }};
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name {{ nginx_server_name }};
ssl_certificate {{ nginx_ssl_cert }};
ssl_certificate_key {{ nginx_ssl_key }};
location / {
proxy_pass http://{{ nginx_upstream }};
proxy_set_header Host $host;
}
}
}
{% else %}
http {
server {
listen 80;
server_name {{ nginx_server_name }};
location / {
proxy_pass http://{{ nginx_upstream }};
}
}
}
{% endif %}
不同环境(开发、测试、生产)通过覆盖变量实现差异化配置,同一套Role代码无需修改即可部署到不同环境。配合ansible-vault加密敏感变量(如数据库密码、SSL私钥),满足安全合规要求。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/ansible-zi-dong-hua-yun-wei-shi-zhan-playbook-bian-xie-yu/