我想遍历很多主机并获取所有手动启动的服务(systemctl start xxxx)而无需先启用(systemctl enable xxxx),反之亦然所有已禁用(systemctldisable xxxx)但仍在运行的服务(因为还没有停止过)。
而不是自动“修复”上述所有发现的问题,我只想将它们输出到我的 shell。
类似 for every 循环遍历
systemctl list-unit-files --state=disabled
并通过 systemctl is-active
运行每一行可能会起作用,但我需要将一个小的 SH 脚本传输到每个主机...
这可以仅由 Ansible 完成吗? (使用带有内核 3.10.x 的 RHEL7 Update 7)
编辑:到目前为止,这是我的剧本,但我无法让循环工作:
---
- hosts: all
gather_facts: no
tasks:
- name: get service facts
service_facts:
- name: show report
when:
- ansible_facts.services[item + '.service'].state == 'running'
- ansible_facts.services[item + '.service'].status == 'disabled'
debug:
msg: "{{ ansible_facts.services[item + '.service'].status == 'disabled' }}"
loop:
ansible_facts.services
关于你的问题
这可以通过 Ansible 单独完成吗?
简短的回答是:是的,当然。这就是 Ansible 的用途。
关于你的标题
如何禁用但运行服务?
和评论
你尝试过ansible.builtin.service_facts吗
我准备了一个简短的测试,它将显示
ansible_facts.services
的结构。
---
- hosts: localhost
become: no
gather_facts: no
tasks:
- name: Gather Service Facts
service_facts:
- name: Show Service Facts
debug:
msg: "{{ ansible_facts.services }}"
以其中一项服务为例
auditd.service:
name: auditd.service
source: systemd
state: running
status: enabled
因此,您需要循环结果集并查找
ansible_facts.services[YOURSERVICE].state
和 ansible_facts.services[YOURSERVICE].status
。
关于你的描述
...已禁用的服务(systemctldisable xxxx)但仍在运行(因为尚未停止)...
您可以查看 如何为
service_facts
声明变量的答案。
关于您的评论
...我如何为所有服务执行条件...
以及已经提到的结果循环,我已经为测试设置添加了
- name: Loop over all services and print name
debug:
msg: "{{ item }}"
when:
- ansible_facts.services[item].state == 'running'
- ansible_facts.services[item].status != 'enabled'
with_items: "{{ ansible_facts.services }}"
发现它有效。
您可能需要调整条件,因为该查询也会报告状态为
static
的服务,例如 dbus
或 systemd-journald
。另请注意,服务也可以具有 unknow
状态。在例子中
splunk.service:
name: splunk.service
source: systemd
state: running
status: unknown
或
systemctl status splunk
● splunk.service - SYSV: Splunk indexer service
Loaded: loaded (/etc/rc.d/init.d/splunk; bad; vendor preset: disabled)
Active: active (running) ...