Ansible 入门指南:快速上手自动化运维

Ansible 入门完全指南:从零开始学习自动化运维

什么是 Ansible

Ansible 是一个开源的自动化运维工具,用于配置管理、应用部署、任务编排等。它具有以下特点:

  • 无代理架构: 不需要在被管理主机上安装客户端
  • 基于 SSH: 使用 SSH 协议连接远程主机
  • 简单易用: 使用 YAML 编写,学习曲线平缓
  • 幂等性: 多次执行结果一致
  • 跨平台: 支持 Linux、Windows、网络设备等

核心概念

控制节点(Control Node)

控制节点是运行 Ansible 的机器,所有 Playbook 都在这里执行。控制节点需要安装 Ansible。

被管理节点(Managed Nodes)

被管理节点是由 Ansible 管理的远程主机,也称为目标主机。被管理节点只需要安装 Python 和 SSH 服务。

Inventory(主机清单)

Inventory 定义了 Ansible 要管理的主机列表,可以按组进行分类。

Playbook

Playbook 是 YAML 格式的配置文件,定义了一系列要执行的任务。

Module(模块)

模块是执行具体任务的工具,如 copy、yum、service 等。

Task(任务)

任务是 Playbook 中的最小执行单元,调用模块完成特定操作。

安装 Ansible

在 Linux 上安装

Ubuntu/Debian

# 更新包列表
sudo apt update

# 安装 Ansible
sudo apt install -y ansible

# 验证安装
ansible --version

CentOS/RHEL

# 安装 EPEL 仓库
sudo yum install -y epel-release

# 安装 Ansible
sudo yum install -y ansible

# 验证安装
ansible --version

在 macOS 上安装

# 使用 Homebrew 安装
brew install ansible

# 验证安装
ansible --version

使用 pip 安装

# 使用 pip 安装
pip install ansible

# 验证安装
ansible --version

配置 SSH 连接

生成 SSH 密钥

# 生成 SSH 密钥对
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# 将公钥复制到被管理主机
ssh-copy-id user@remote_host

# 测试连接
ssh user@remote_host

配置 SSH 配置文件

编辑 ~/.ssh/config 文件:

Host server1
    HostName 192.168.1.10
    User ansible
    Port 22
    IdentityFile ~/.ssh/id_rsa

Host server2
    HostName 192.168.1.11
    User ansible
    Port 22
    IdentityFile ~/.ssh/id_rsa

创建 Inventory 文件

创建 inventory.ini 文件:

[webservers]
192.168.1.10
192.168.1.11

[dbservers]
192.168.1.20
192.168.1.21

[production:children]
webservers
dbservers

验证连接

# 测试所有主机的连接
ansible all -i inventory.ini -m ping

# 测试特定组的连接
ansible webservers -i inventory.ini -m ping

# 使用 SSH 配置测试
ansible all -m ping

第一个 Playbook

创建 hello_world.yml 文件:

---
- name: Hello World Playbook
  hosts: all
  become: yes
  
  tasks:
    - name: Print hello world
      debug:
        msg: "Hello, Ansible!"
    
    - name: Ensure package cache is updated (Ubuntu/Debian)
      apt:
        update_cache: yes
        cache_valid_time: 3600
      when: ansible_os_family == "Debian"

运行 Playbook:

# 运行 Playbook
ansible-playbook -i inventory.ini hello_world.yml

# 检查 Playbook 语法
ansible-playbook --syntax-check hello_world.yml

# 列出任务(不执行)
ansible-playbook --list-tasks hello_world.yml

常用 Ad-hoc 命令

# 检查主机连接
ansible all -m ping

# 执行命令
ansible all -m shell -a "uptime"

# 复制文件
ansible all -m copy -a "src=/tmp/test.txt dest=/tmp/"

# 安装软件包
ansible webservers -m yum -a "name=nginx state=present"

# 启动服务
ansible webservers -m service -a "name=nginx state=started"

# 查看主机信息
ansible all -m setup | less

最佳实践

  • 使用版本控制: 将所有 Playbook 和配置文件纳入 Git 管理
  • 模块化设计: 将复杂的任务拆分为多个 Roles
  • 幂等性: 确保任务可以安全地多次执行
  • 错误处理: 使用 ignore_errors 和 failed_when 处理错误
  • 安全第一: 使用 Ansible Vault 加密敏感信息

总结

Ansible 是一个强大而简单的自动化工具,适合各种规模的运维场景。通过本文的学习,你已经掌握了 Ansible 的基础概念、安装方法和第一个 Playbook 的编写。接下来可以深入学习 Inventory 配置、Playbook 语法、变量管理等高级内容。

发表回复

后才能评论