Ansible批量查看服务状态首选systemctl命令配合command模块,先验证systemd支持(cat /proc/1/comm或systemctl --version),再用systemctl is-active/is-enabled/status查状态;service模块仅用于兼容SysV旧系统,会尝试变更状态而非纯查询。

用 Ansible 批量查看服务运行状态,核心是调用 service 或 systemd 模块(取决于系统版本),配合 state=started 或 status 操作。CentOS 7+/RHEL 8+ 默认用 systemd,推荐统一用 systemctl 命令结合 command 模块,更直观、兼容性更好。
确认目标主机支持 systemctl
先快速验证被管节点是否为 systemd 系统:
-
ansible all -a "cat /proc/1/comm" —— 返回
systemd表示支持 - ansible all -a "systemctl --version" —— 有输出即可用
用 command 模块查指定服务状态
最常用、最稳妥的方式,直接执行 systemctl status 命令,返回原始输出,便于人工判断:
-
ansible web_servers -a "systemctl is-active nginx" —— 返回
active或inactive - ansible db_group -a "systemctl is-enabled mysqld" —— 查是否开机自启
-
ansible all -a "systemctl status sshd --no-pager | head -n 10" —— 查详细状态摘要(加
--no-pager避免卡住)
用 service 模块查状态(兼容旧版 SysV)
适用于 CentOS 6 或混合环境,但不推荐新系统使用:
-
ansible all -m service -a "name=httpd state=started" —— 返回
changed: false表示已运行;failed表示异常 - 注意:service 模块本身不提供“只查不改”的纯状态检查模式,它会尝试确保服务处于指定状态,所以用于“查看”时需理解其语义是“校验是否已启动”
批量汇总成表格格式(进阶)
若需结构化输出,可写简单 playbook,用 register + debug 提取关键字段:
- 创建
check-service.yml:
--- - hosts: all tasks: - name: Get nginx status command: systemctl is-active nginx register: nginx_status ignore_errors: true - name: Show result debug: msg: "{{ inventory_hostname }}: {{ nginx_status.stdout | default('unknown') }}"
- 运行:ansible-playbook check-service.yml


















