介绍
service 模块用于管理系统服务(启动/停止/重启/开机自启),兼容 sysvinit、systemd 等。
基础语法
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 服务
ansible web -m service -a "name=nginx state=started" -b -i ansible_client.ini
2. 停止 nginx
ansible web -m service -a "name=nginx state=stopped" -b -i ansible_client.ini
3. 重启 nginx
ansible web -m service -a "name=nginx state=restarted" -b -i ansible_client.ini
4. 重载 nginx 配置(平滑生效)
ansible web -m service -a "name=nginx state=reloaded" -b -i ansible_client.ini
5. 设置开机自启(不改变当前运行状态)
ansible web -m service -a "name=nginx enabled=yes" -b -i ansible_client.ini
6. 同时:开机自启 + 启动服务(最常用组合)
ansible web -m service -a "name=nginx state=started enabled=yes" -b -i ansible_client.ini
7. 关闭开机自启
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,不会重复启动。
常见坑
- 服务名称写错:不同系统服务名不一样,CentOS7 ssh 服务叫
sshd不是ssh - reload 不是所有服务都支持,不支持 reload 的服务用
state=reloaded会报错,改用 restarted - service 模块不执行 daemon-reload
systemd 场景修改 service 单元文件后,需要先执行 daemon-reload,service模块做不到,要用systemd模块:ansible web -m systemd -a "name=myapp daemon_reload=yes" - 权限:启停服务需要 root,ansible 命令记得加
-b(提权 become)ansible web -b -m service -a "name=nginx state=started" - 老 CentOS6(sysvinit):
pattern参数用来匹配进程,防止无法识别服务状态,现代系统基本不用。