Ansible 2.9如何用systemd模块检查服务运行状态?
Ansible 2.9中用systemd模块查询服务状态的解决方案
问题背景
在Ansible 2.9的任务里,需要根据服务是否启动来执行对应操作,最初的实现代码如下:
- name: 'Check status of phpfpm-www56 service' command: 'systemctl is-active --quiet php5.6-fpm' register: cmd_fpm56_status - name: 'Some task' command: 'somescript' when: cmd_fpm56_status.rc == 0
运行ansible lint时触发两个错误:command-instead-of-module: systemctl used in place of systemd moduleno-changed-when: Commands should not change things if nothing needs doing
需要确认是否可以用systemd模块仅查询服务状态,同时解决lint错误。
可行方案
完全可以用systemd模块实现仅查询服务状态的需求,以下提供两种可靠的实现方式:
方式一:用systemd模块配合检查模式
- name: 'Check if php5.6-fpm is active' systemd: name: php5.6-fpm state: started check_mode: yes register: fpm56_status - name: 'Run somescript when php5.6-fpm is active' command: 'somescript' when: not fpm56_status.changed
- 原理:
check_mode: yes会让systemd模块仅模拟执行启动操作,不会真的修改服务状态。如果服务已经处于启动状态,changed字段会返回false;若未启动则返回true,以此判断服务是否运行。 - 这种写法完全符合Ansible模块使用规范,能通过ansible lint检查。
方式二:收集服务事实(适合多服务查询场景)
- name: 'Gather all service status facts' service_facts: - name: 'Run somescript when php5.6-fpm is active' command: 'somescript' when: ansible_facts.services["php5.6-fpm.service"].state == "running"
- 原理:
service_facts模块会一次性收集目标主机上所有服务的状态信息,存储在ansible_facts.services字典中,后续直接通过键值对获取指定服务的状态即可。 - 优势:无需为单个服务单独写查询任务,后续多个任务可复用收集到的事实数据。
内容的提问来源于stack exchange,提问作者Darko Miletic
相关产品推荐
相关产品推荐

