Ansible教程:Ad-hoc 命令用法-service模块详解 作者:马育民 • 2026-09-25 21:32 • 阅读:10001 # 介绍 `service` 模块用于**管理系统服务**(启动/停止/重启/开机自启),兼容 sysvinit、systemd 等。 # 基础语法 ```bash ansible 主机组 -m service -a "参数" ``` **参数:** - `-m service`:指定使用 service 模块 - `-a "xxx"`:模块参数 **注意:**ansible 的 `service` 是**跨初始化系统通用模块**;如果目标机器是 systemd,还有专门 `systemd` 模块,支持更多特性(如 daemon-reload)。 # 常用参数 | 参数 | 说明 | 可选值 | |---|---|---| | **`name`** | **必填**,服务名称 | 如 `nginx`、`sshd`、`firewalld` | | **`state`** | 服务状态 | `started`启动、`stopped`停止、`restarted`重启、`reloaded`平滑重载(不中断连接) | | `enabled` | 是否开机自启 | `yes` / `no` | | `sleep` | 重启时,stop之后等待多少秒再start | 数字,部分版本支持 | | `pattern` | 匹配进程名(老sysvinit系统用,systemd基本不用) | 字符串 | ### 区分 - `restarted`:先停再启,会断开现有连接 - `reloaded`:重新加载配置,**不中断服务连接**,前提是服务本身支持 reload # 例子 ### 1. 启动 nginx 服务 ```bash ansible web -m service -a "name=nginx state=started" -b -i ansible_client.ini ``` ### 2. 停止 nginx ```bash ansible web -m service -a "name=nginx state=stopped" -b -i ansible_client.ini ``` ### 3. 重启 nginx ```bash ansible web -m service -a "name=nginx state=restarted" -b -i ansible_client.ini ``` ### 4. 重载 nginx 配置(平滑生效) ```bash ansible web -m service -a "name=nginx state=reloaded" -b -i ansible_client.ini ``` ### 5. 设置开机自启(不改变当前运行状态) ```bash ansible web -m service -a "name=nginx enabled=yes" -b -i ansible_client.ini ``` ### 6. 同时:开机自启 + 启动服务(最常用组合) ```bash ansible web -m service -a "name=nginx state=started enabled=yes" -b -i ansible_client.ini ``` ### 7. 关闭开机自启 ```bash ansible web -m service -a "name=nginx enabled=no" -b -i ansible_client.ini ``` # 返回结果字段说明 执行后返回 json,重点看: - `changed`:`true` 代表服务状态发生变更;`false` 代表已经是目标状态,无改动(幂等性) - `rc`:返回码,0=成功 - `stderr`/`stdout`:命令输出 ### **幂等特性** 这是 ansible 模块核心。 例:服务已经 running,再次执行 `state=started` → `changed=false`,不会重复启动。 # 常见坑 1. **服务名称写错**:不同系统服务名不一样,CentOS7 ssh 服务叫 `sshd` 不是 `ssh` 2. **reload 不是所有服务都支持**,不支持 reload 的服务用 `state=reloaded` 会报错,改用 restarted 3. **service 模块不执行 daemon-reload** systemd 场景修改 service 单元文件后,需要先执行 daemon-reload,`service` 模块做不到,要用 `systemd` 模块: ```bash ansible web -m systemd -a "name=myapp daemon_reload=yes" ``` 4. **权限**:启停服务需要 root,ansible 命令记得加 `-b`(提权 become) ```bash ansible web -b -m service -a "name=nginx state=started" ``` 5. 老 CentOS6(sysvinit):`pattern` 参数用来匹配进程,防止无法识别服务状态,现代系统基本不用。 原文出处:/show_1GW478har1vH.html