我正在所有主机上运行剧本 sttaus_check
。它将从所有主机获取各个进程的状态并打印到控制台。
我有不同的任务,例如针对不同组的 Mongo & Rabbitmq
groupA
& groupB
[groupA]
127.0.0.1
127.0.0.2
127.0.0.3
[groupB]
127.0.0.2
127.0.0.3
status_check.yaml
- hosts: all
tasks:
- name: Check Mongo service status when multi region is false
shell: ps -ef| grep [m]ongo 1>/dev/null || [ $? -eq 0 ] && echo "UP" || echo "DOWN"
register: mongod_status
no_log: True
when:
- "'groupA' in group_names"
- name: Format mongo status
when:
- "'groupA' in group_names"
import_role:
name: library
tasks_from: format_process_status
vars:
Service: mongod
group: groupA
status: "{{ mongod_status.stdout_lines }}"
- name: Check Rabbitmq service status
shell: ps -ef| grep [b]eam.smp 1>/dev/null || [ $? -eq 0 ] && echo "UP" || echo "DOWN"
register: rmq_status
when:
- "'groupB' in group_names"
- name: Format rabbitmq status
when:
- "'clusterB' in group_names"
import_role:
name: library
tasks_from: format_process_status
vars:
Service: rabbitmq
group: groupB
status: "{{ rmq_status.stdout_lines }}"
TL;DR
format_process_status 扮演库角色:
- name: Print {{ Service }} Stauts from each host of group
block:
- name: Converting {{Service}} status into list
no_log: True
set_fact:
status_list: "{{ status| list}}"
- block:
- name: Extract hostvars of the hosts from the group and create the list of the host-status dictionaries
no_log: True
set_fact:
status_dict: "{{ groups[group]|map('extract', hostvars)|list|json_query('[].{host: ansible_hostname,status: status_list }') }}"
- name: Formating status_dict into readable format
no_log: True
set_fact:
service_status: "{{ service_status|default({}) | combine ( {item.host : item.status|join('\n') }) }}"
with_items: "{{ status_dict }}"
- name: Converting generic dict var name to {{ Service }}_status specific var
no_log: True
set_fact:
"{{ Service}}_status": "{{ service_status }}"
- name: Below is the {{Service}} Service status from each host of group
debug: var={{ Service }}_status
run_once: true
以上在从 mongo
获取 groupA
状态时工作正常。下面是输出。
ok: [127.0.0.1] => {
"mongod_status": {
"127.0.0.1": "UP",
"127.0.0.2": "UP",
"127.0.0.3": "UP"
}
}
但是当从 rabbitmq
获取 groupB
时,它跳过主机 127.0.0.1
因为它不是 groupB
的一部分,因为 run_once
在 {{ 1}} 带有 format_process_status.yml
的所有任务都将被跳过。
Rabbitmq 输出:-
run_once
我怎么能不考虑(甚至不跳过)不属于 TASK [library : debug]
skipping: [127.0.0.1]
ok: [127.0.0.2] => {
"status_list": [
"UP"
]
}
ok: [127.0.0.3] => {
"status_list": [
"UP"
]
}
TASK [library : Extract host vars of the hosts from the group and create the list of the host-status dictionaries]
skipping: [127.0.0.1]
TASK [library : Formating status_dict into readable format] **********
skipping: [127.0.0.1]
的主机。或者我怎样才能实现所有主机的输出?有没有更好的办法?
注意:因为我有多个小组和各自的流程,所以期待一个不创建单独剧本的解决方案。