温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用Ansible自动化运维

发布时间:2026-09-21 06:55:58 来源:亿速云 阅读:84 作者:小樊 栏目:系统运维

下面从概念 → 核心组件 → 实战示例 → 最佳实践四个层面,系统讲如何用 Ansible 做自动化运维


一、Ansible 是什么(为什么用它)

Ansible 是一款**无代理(agentless)**的自动化运维工具,基于 SSH 管理目标主机。

核心优势

  • ✅ 无需在目标机安装客户端
  • ✅ 使用 YAML 编写,易读易维护
  • ✅ 幂等性(重复执行结果一致)
  • ✅ 适合:配置管理、批量部署、应用发布、日常运维

二、Ansible 核心概念

1️⃣ 控制节点(Control Node)

  • 安装 Ansible 的机器(通常是运维机 / 跳板机)
  • Python 环境即可

2️⃣ 被控节点(Managed Nodes)

  • 被管理的服务器
  • 只需支持 SSH + Python

3️⃣ Inventory(主机清单)

定义“管理哪些机器”

[web]
192.168.1.10
192.168.1.11

[db]
192.168.1.20

4️⃣ Module(模块)

执行具体操作的单位
常见模块:

  • command / shell
  • yum / apt
  • copy
  • service
  • user
  • template

5️⃣ Playbook(剧本)

用 YAML 描述“做什么”


三、快速上手示例

1️⃣ 安装 Ansible

# CentOS / RHEL
yum install -y ansible

# Ubuntu
apt install -y ansible

2️⃣ 配置 Inventory

# /etc/ansible/hosts
[web]
192.168.1.10
192.168.1.11

3️⃣ 测试连通性

ansible all -m ping

四、Playbook 实战示例

示例 1:安装 Nginx 并启动

# deploy_nginx.yaml
- hosts: web
  become: yes
  tasks:
    - name: Install nginx
      yum:
        name: nginx
        state: present

    - name: Start nginx
      service:
        name: nginx
        state: started
        enabled: yes

执行:

ansible-playbook deploy_nginx.yaml

示例 2:批量分发配置文件

- hosts: web
  become: yes
  tasks:
    - name: Copy nginx config
      copy:
        src: ./nginx.conf
        dest: /etc/nginx/nginx.conf
      notify: Restart nginx

  handlers:
    - name: Restart nginx
      service:
        name: nginx
        state: restarted

示例 3:使用变量(推荐)

- hosts: web
  vars:
    pkg_name: nginx
  tasks:
    - name: Install package
      yum:
        name: "{{ pkg_name }}"
        state: present

五、Roles(标准项目结构)

适合中大型运维项目

nginx/
├── tasks/main.yaml
├── handlers/main.yaml
├── templates/nginx.conf.j2
├── vars/main.yaml

使用:

- hosts: web
  roles:
    - nginx

✅ 优点:

  • 结构清晰
  • 易复用
  • 易维护

六、常见自动化运维场景

场景 Ansible 用法
批量装软件 yum/apt
配置管理 copy/template
服务启停 service/systemd
用户管理 user
定时任务 cron
应用发布 git + copy + service
安全加固 写 role

七、企业级最佳实践

使用 SSH Key,不用密码
拆分环境(prod / test)Inventory
敏感信息用 Ansible Vault

ansible-vault encrypt vars.yaml

幂等性设计(state=present / absent)
CI/CD 集成(GitLab + Ansible)


八、学习路线建议

  1. 熟悉 Linux + SSH
  2. 手写 10 个 Playbook
  3. 学会 Roles
  4. 结合 Git + CI
  5. 向自动化平台演进(AWX / Ansible Tower)

如果你愿意,我可以:

  • ✅ 给你一套完整 Ansible 项目模板
  • ✅ 按你的业务(Web / DB / K8s)定制示例
  • ✅ 教你如何用 Ansible 做发布系统

你现在的运维场景是什么?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI