《安全配置自动化实现路径》
第4章 Ansible核心基础
4. Ansible核心基础:架构、安装配置、Inventory管理与Ad-Hoc命令
4.1 Ansible架构全景
Ansible采用无代理(Agentless)架构,通过SSH协议直接管理目标主机。其核心组件包括:
4.2 安装配置
Ansible支持多种安装方式,推荐使用pip或系统包管理器安装。
安装步骤
- 更新系统包:
sudo yum update -y(CentOS/RHEL) - 安装EPEL源:
sudo yum install epel-release -y - 安装Ansible:
sudo yum install ansible -y - 验证安装:
ansible --version
配置文件结构
/etc/ansible/ ├── ansible.cfg # 主配置文件 ├── hosts # Inventory清单文件 └── roles/ # 角色目录
4.3 Inventory管理
Inventory定义了Ansible管理的主机列表和分组信息,支持静态和动态两种模式。
静态Inventory示例(INI格式)
# /etc/ansible/hosts [web_servers] web1.example.com web2.example.com ansible_user=admin ansible_port=2222 [db_servers] db1.example.com ansible_ssh_private_key_file=/path/to/key [cache_servers] redis1.example.com [all:vars] ansible_user=root ansible_ssh_common_args='-o StrictHostKeyChecking=no'
常用变量说明
4.4 Ad-Hoc命令
Ad-Hoc命令用于执行一次性任务,无需编写Playbook,适合快速操作和测试。
常用Ad-Hoc命令示例
常用模块速查
- ping — 测试主机连通性
- command — 执行shell命令(不支持管道/重定向)
- shell — 执行shell命令(支持管道/重定向)
- copy — 文件复制
- yum/apt — 包管理
- service/systemd — 服务管理
- file — 文件/目录属性管理
- user — 用户管理
Ad-Hoc命令实战示例
# 1. 测试所有主机连通性 ansible all -m ping # 2. 查看web服务器组的内存使用情况 ansible web_servers -m shell -a "free -h" # 3. 在db服务器组创建用户 ansible db_servers -m user -a "name=deploy state=present groups=wheel" # 4. 分发配置文件到所有主机 ansible all -m copy -a "src=./nginx.conf dest=/etc/nginx/nginx.conf mode=0644" # 5. 重启服务并检查状态 ansible web_servers -m service -a "name=nginx state=restarted" ansible web_servers -m shell -a "systemctl status nginx | head -5"