从 0 到 1:使用 Ansible 自动化运维 Linux 服务器全流程
Ansible 是一款强大的 IT 自动化工具,广泛用于服务器配置管理、软件部署和任务自动化。本文将带你从零开始,学习如何使用 Ansible 对 Linux 服务器进行自动化运维,涵盖 Ansible 的基本概念、安装配置、常见 Playbook 编写,以及实际运维案例。
一、Ansible 简介:为什么选择 Ansible?
在 DevOps 时代,自动化工具至关重要,Ansible 以其无代理(Agentless)、**声明式(Declarative)和可扩展(Scalable)**等特点,成为 IT 运维的首选。
o 无代理架构:直接 SSH 连接,无需在目标服务器安装客户端。
o 易学易用:YAML 语法,简单易读,适合初学者。
o 强大的模块化:支持上千个内置模块,涵盖系统管理、网络设备、云平台等。
二、环境准备:安装 Ansible
1. 服务器环境要求
o 控制节点(安装 Ansible 的主机):Ubuntu 20.04 / CentOS 7 及以上
o 目标服务器(被管理的 Linux 服务器):Ubuntu、CentOS、Debian 等
2. 安装 Ansible
在 CentOS 上安装:
sudo yum install -y epel-release
sudo yum install -y ansible
在 Ubuntu/Debian 上安装:
sudo apt update
sudo apt install -y ansible
验证安装:
ansible --version
三、Ansible 配置管理
1. 配置主机清单(Inventory)
Ansible 通过 inventory 文件管理被控主机,默认位置 /etc/ansible/hosts:
[web_servers]
192.168.1.100
192.168.1.101
[db_servers]
192.168.1.200
测试 Ansible 连接:
ansible all -m ping
如果返回 "pong",表示连接成功。
四、编写第一个 Ansible Playbook
Playbook 是 Ansible 自动化任务的核心,使用 YAML 语法定义。
示例:自动化安装 Nginx
创建 Playbook 文件 install_nginx.yml:
- hosts: web_servers
become: yes
tasks:
- name: 安装 Nginx
yum:
name: nginx
state: present
- name: 启动 Nginx
service:
name: nginx
state: started
运行 Playbook:
ansible-playbook install_nginx.yml
执行后,所有 web_servers 组内的服务器都会自动安装并启动 Nginx。
五、高级自动化案例:批量管理服务器
1. 创建用户并设置 SSH 免密登录
- hosts: all
become: yes
tasks:
- name: 创建新用户
user:
name: deploy
shell: /bin/bash
groups: sudo
- name: 设置 SSH 免密登录
authorized_key:
user: deploy
state: present
key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
2. 监控服务器状态并发送通知
- hosts: all
tasks:
- name: 检查 CPU 使用率
shell: "top -bn1 | grep 'Cpu' | awk '{print $2}'"
register: cpu_usage
- name: 发送通知
debug:
msg: "当前 CPU 使用率:{{ cpu_usage.stdout }}%"
六、总结
本教程带你从零开始学习 Ansible,掌握了基本的安装、主机管理、Playbook 编写及高级自动化案例。使用 Ansible,你可以轻松管理数百台 Linux 服务器,提高运维效率。如果你对 DevOps 和自动化运维感兴趣,不妨尝试编写自己的 Playbook,实现更多自动化任务!
下期预告:
如何使用 Ansible 自动化部署 Docker 和 Kubernetes 集群,敬请关注!
互动讨论
你是否在实际运维中使用过 Ansible?有哪些经验或问题?欢迎在评论区分享交流!