Ansible 自动化运维介绍

Ansible自动化介绍

Ansible是一种开源的自动化运维工具,用于配置管理、应用部署和任务自动化。其核心基于YAML语言编写的Playbook,通过SSH协议与目标节点通信,无需在被控端安装额外代理。关键组件包括:

  • Inventory:定义目标主机和分组;
  • Playbook:描述自动化任务的YAML文件;
  • Module:执行特定任务的代码单元 (如文件操作、包管理);

环境准备与安装

在Linux控制节点或主节点上安装Ansible:

bash 复制代码
# Ubuntu/Debian  
sudo apt update && sudo apt install ansible  

# CentOS/RHEL  
sudo yum install ansible  

# macOS  
brew install ansible  

验证安装:

bash 复制代码
ansible --version  

配置Inventory文件

默认Inventory文件路径为/etc/ansible/hosts,也可自定义。示例:

ini 复制代码
[web_servers]  
192.168.1.10 ansible_user=ubuntu  
192.168.1.11 ansible_user=ubuntu  

[db_servers]  
db.example.com ansible_ssh_private_key_file=/path/to/key.pem  

编写第一个Playbook

创建deploy_nginx.yml文件,部署Nginx:

yaml 复制代码
---  
- name: Install and start Nginx  
  hosts: web_servers  
  become: yes  
  tasks:  
    - name: Install Nginx  
      apt:  
        name: nginx  
        state: present  
      when: ansible_os_family == "Debian"  

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

执行Playbook与常用命令

运行Playbook:

bash 复制代码
ansible-playbook -i inventory_file deploy_nginx.yml  

常用命令:

  • 测试主机连通性:ansible all -m ping
  • 临时执行命令:ansible web_servers -a "uptime"

进阶功能与最佳实践

变量管理

  • 在Playbook中定义变量:

    yaml 复制代码
    vars:  
      http_port: 80  
  • 使用外部变量文件(如group_vars/web_servers.yml)。

角色(Roles)

通过模块化组织Playbook:

bash 复制代码
ansible-galaxy init roles/nginx  

目录结构示例:

复制代码
roles/nginx/  
├── tasks/  
├── handlers/  
├── templates/  

错误处理

  • 使用ignore_errors: yes忽略任务失败。
  • 通过blockrescue实现异常捕获。

性能优化技巧

  • 启用SSH长连接:在ansible.cfg中设置:

    ini 复制代码
    [ssh_connection]  
    ssh_args = -o ControlMaster=auto -o ControlPersist=60s  
  • 使用strategy: free允许异步任务执行。

通过上述方法,Ansible可实现从简单配置到复杂部署的自动化流程,显著提升运维效率。

相关推荐
wang_shu_mo_ran10 小时前
网络编程(一):网络编程初识
运维·服务器·网络
姚青&11 小时前
持续交付与 DevOps 体系
运维·devops
ton_tom11 小时前
设备驱动程序编程-Linux2.6.10-kdb安装-32位
linux·运维·服务器
Elastic 中国社区官方博客11 小时前
谁来评判评判者?在 Elasticsearch Workflows 中使用 LLM-as-a-Judge
大数据·运维·人工智能·elasticsearch·搜索引擎·ai·全文检索
techdashen11 小时前
Uber 的全局限流系统:从零散 Redis 限流到服务网格里的自动化流量保护
数据库·redis·自动化
SSO_Crown12 小时前
AI 招聘管理系统深度评测与选型指南
大数据·运维·人工智能
志栋智能12 小时前
超自动化安全如何优化安全运营成本?
人工智能·安全·自动化
cft56200_ln12 小时前
gPTP Master 报文目的 MAC 地址
运维·服务器·网络
曦尧13 小时前
RuView:用普通 WiFi 信号实现穿墙空间感知与生命体征监测
ai·自动化