单纯的学习笔记。Ansible 是一个强大的自动化运维工具,提供了大量模块来完成各种任务,平常用来管理大量服务器或者虚拟机还是很方便的。
🧱 1. 基础操作模块
| 模块 | 说明 | 示例 |
|---|---|---|
| ping | 测试连通性 | ansible all -m ping |
| shell | 执行 shell 命令(支持管道) | ansible all -m shell -a "echo hello“ |
| script | 运行本地脚本 | ansible all -m script -a “./deploy.sh” |
| raw | 不依赖 Python 环境直接执行命令 | ansible all -m raw -a “yum install -y python3” |
📂 2. 文件与目录管理
| 模块 | 说明 | 示例 |
|---|---|---|
| copy | 拷贝文件/目录到远程主机 | ansible all -m copy -a “src=/root/file.txt dest=/tmp/file.txt” |
| file | 设置文件权限、拥有者、目录状态) | ansible all -m file -a “path=/tmp/logs state=directory mode=755” |
| fetch | 从远程主机取回文件 | ansible all -m fetch -a “src=/var/log/messages dest=/tmp/logs” |
| lineinfile | 修改文件中的一行 | ansible all -m lineinfile -a “path=/etc/hosts line=‘127.0.0.1 test.local’” |
📦 3. 软件包管理
| 模块 | 说明 | 示例 |
|---|---|---|
| yum | RHEL/CentOS 安装包 | ansible all -m yum -a “name=httpd state=present” |
| apt | Debian/Ubuntu 安装包 | ansible all -m apt -a “name=nginx state=present” |
| package | 跨平台统一安装模块 | ansible all -m package -a “name=git state=latest” |
🖥️ 4. 服务与进程控制
| 模块 | 说明 | 示例 |
|---|---|---|
| service | 管理系统服务 | ansible all -m service -a “name=nginx state=restarted” |
| systemd | 更现代的服务管理 | ansible all -m systemd -a “name=docker enabled=yes state=started” |
| cron | 管理计划任务 | ansible all -m cron -a “name=‘backup’ minute=0 hour=2 job=‘/bin/backup.sh’” |
👤 5. 用户与权限
| 模块 | 说明 | 示例 |
|---|---|---|
| user | 管理用户账户 | ansible all -m user -a “name=devuser state=present” |
| group | 管理用户组 | ansible all -m group -a “name=developers state=present” |
| authorized_key | 设置 SSH 公钥登录 | ansible all -m authorized_key -a “user=root key=‘{{ lookup(‘file’, ‘/root/id_rsa.pub’) }}’” |
🌐 6. 网络相关
| 模块 | 说明 | 示例 |
|---|---|---|
| hostname | 设置主机名 | ansible all -m hostname -a “name=node01” |
| firewalld | 管理 firewalld 防火墙 | ansible all -m firewalld -a “port=80/tcp permanent=true state=enabled immediate=yes” |
| iptables | 设置 iptables(用 script/shell 调用较多) | ansible all -m shell -a “iptables -A INPUT -p tcp --dport 22 -j DROP” |

