我正在尝试比较Linux服务器上重启之前/之后运行的服务。但是我无法获得输出差异的信息。
我目前拥有的功能将前/后状态输出到磁盘。但我希望直接将输出注册为变量
- name: populate service facts
service_facts:
register: facts
- name: Outputting running services
debug: var=item
with_items: "{{ facts|json_query(query)}}"
vars:
query: 'ansible_facts.services.* | [?state == `running`].name'
应该以类似于以下内容的函数结尾
- name: Missing running services
debug:
msg: {{ item }}
with_items:
- {{ facts_pre }}
- {{ facts_post }}
vars:
query: 'ansible_facts.services.* | [?state == `running`].name'
when: facts_pre.ansible_facts.services != facts_post.ansible_facts.services
结果应该类似于在重新启动前显示以下状态
ok: [hostname] => (item=NetworkManager.service) => {
"item": "NetworkManager.service"
}
ok: [hostname] => (item=systemd-udevd.service) => {
"item": "systemd-udevd.service"
}
ok: [hostname] => (item=sshd.service) => {
"item": "sshd.service"
}
ok: [hostname] => (item=systemd-journald.service) => {
"item": "systemd-journald.service"
}
并且由于某种原因在启动过程中记录日志失败
ok: [hostname] => (item=NetworkManager.service) => {
"item": "NetworkManager.service"
}
ok: [hostname] => (item=systemd-udevd.service) => {
"item": "systemd-udevd.service"
}
ok: [hostname] => (item=sshd.service) => {
"item": "sshd.service"
}
它将systemd-journald.service注册到它自己的变量中。
答案 0 :(得分:1)
查询给出了正在运行的服务列表
- service_facts:
- set_fact:
running_services_A: "{{ ansible_facts.services|dict2items|
json_query('[?value.state == `running`].key') }}"
“比较运行中的服务” 使用difference过滤器。例如
- debug:
msg: "Services running at A but not at B
{{ running_services_A|difference(running_services_B) }}"
(未经测试)
service_facts
的输出。变量 ansible_facts.services
是自动创建的。参见service_facts。答案 1 :(得分:0)
您可以尝试使用with_items
子句,在重新启动前后,您拥有列表的intersection
。它将显示两个列表之间的所有差异。
使用sleep
任务对剧本进行采样,以便为您提供足够的时间来停止/启动另一个会话中的服务,以便您可以在facts_post
变量中捕获它:
---
- hosts: localhost
gather_facts: false
vars:
web_folder:
tasks:
- name: populate service facts BEFORE
service_facts:
register: facts_pre
- name: sleep to stop/start a service
shell: sleep 10
- name: populate service facts AFTER
service_facts:
register: facts_post
- name: Missing running services
debug:
var: item
with_items:
- "{{ facts_pre | json_query(query) | symmetric_difference(facts_post | json_query(query)) }}"
vars:
query: 'ansible_facts.services.* | [?state == `running`].name'
希望有帮助。