简介

Ansible是一个开源的自动化工具,用于配置管理、应用部署、任务编排等IT运维工作。它使用简单的YAML语法描述自动化任务,无需在被管理主机上安装客户端,通过SSH进行通信,是实现基础设施即代码(IaC)的理想工具。

主要特点

  • 无代理架构:使用SSH进行通信,无需安装客户端
  • 简单易用:使用YAML语法,学习曲线平缓
  • 可重复执行:任务具有幂等性,可重复运行
  • 模块化设计:丰富的模块库,支持自定义扩展
  • 强大的社区:活跃的社区支持,大量现成的角色和playbook

安装配置

在不同系统上安装

Ubuntu/Debian:

sudo apt update sudo apt install ansible

CentOS/RHEL:

sudo yum install epel-release sudo yum install ansible

macOS:

brew install ansible

使用pip安装:

pip install ansible

验证安装

ansible --version

基本概念

核心组件

  • Control Node:安装Ansible的主机
  • Managed Nodes:被管理的目标主机
  • Inventory:主机清单,定义目标主机组
  • Playbooks:任务剧本,定义自动化任务
  • Roles:可重用的任务集合
  • Modules:功能模块,执行具体操作

基本命令

执行ad-hoc命令:

ansible all -m ping ansible webservers -m shell -a "uptime"

执行playbook:

ansible-playbook playbook.yml

Playbook编写

基本结构

--- - name: Configure webservers hosts: webservers become: yes tasks: - name: Install nginx apt: name: nginx state: present - name: Start nginx service service: name: nginx state: started enabled: yes

变量使用

--- - name: Deploy application hosts: app_servers vars: app_port: 8080 app_version: "1.0.0" tasks: - name: Deploy application template: src: app.conf.j2 dest: /etc/app/config.conf

主机清单管理

静态Inventory

[webservers] web1.example.com web2.example.com [dbservers] db1.example.com db2.example.com [production:children] webservers dbservers

动态Inventory

使用脚本或插件动态生成主机清单,常用于云环境:

#!/usr/bin/env python import json inventory = { 'webservers': { 'hosts': ['web1.example.com', 'web2.example.com'], 'vars': { 'http_port': 80 } } } print(json.dumps(inventory))

Roles开发

Role目录结构

roles/ webserver/ tasks/ main.yml handlers/ main.yml templates/ nginx.conf.j2 vars/ main.yml defaults/ main.yml meta/ main.yml

使用Role

--- - name: Configure web servers hosts: webservers roles: - webserver - { role: database, db_name: myapp }

最佳实践

目录结构

ansible-project/ inventory/ production/ staging/ group_vars/ all/ webservers/ host_vars/ web1.example.com/ roles/ common/ webserver/ database/ site.yml webservers.yml dbservers.yml

开发建议

  • 使用版本控制管理代码
  • 合理使用变量和模板
  • 编写可重用的Role
  • 遵循命名规范
  • 做好测试和文档