yaml如下:
---
- name: Check running time service
hosts: all
gather_facts: no
vars:
time_service: unknown
tasks:
# 检查Chrony进程
- name: Check chronyd process
shell:
cmd: pgrep -x chronyd >/dev/null && echo "running" || exit 1
executable: /bin/bash
register: check_chrony
ignore_errors: yes
changed_when: false
# 检查NTP进程
- name: Check ntpd process
shell:
cmd: pgrep -x ntpd >/dev/null && echo "running" || exit 1
executable: /bin/bash
register: check_ntp
ignore_errors: yes
changed_when: false
# 判断结果
- name: Determine service
set_fact:
time_service: >-
{% if check_chrony.rc == 0 %}
chrony
{% elif check_ntp.rc == 0 %}
ntp
{% else %}
none
{% endif %}
# 显示检查结果
- name: Show result
debug:
msg: |
节点 {{ inventory_hostname }} 时间服务:
- 当前运行服务: {{ time_service | upper }}
- 检测时间: {{ ansible_date_time.iso8601 }}
- 详细状态:
{% if time_service == 'chrony' %}
Chrony进程PID: {{ check_chrony.stdout }}
{% elif time_service == 'ntp' %}
NTP进程PID: {{ check_ntp.stdout }}
{% else %}
未检测到运行的时间服务
{% endif %}
执行:
ansible-playbook check_time_service.yml -i your_inventory
说明:
以上yaml脚本兼容所有主流Linux发行版(RHEL/CentOS 6/7/8, Ubuntu, Debian等)
其次使用pgrep命令直接检测进程,来快速定位。