gpt4 book ai didi

ansible - 如何使用 ansible_facts 仅列出正在运行的服务

转载 作者:行者123 更新时间:2023-12-02 01:46:44 27 4
gpt4 key购买 nike

如何在不提供像第一个代码那样提供列表的情况下,以 state=='running' 列出系统的所有服务?

- name: Populate service facts
service_facts:
no_log: true
register: inspect_services2
when: "ansible_facts.services[] is defined and ansible_facts.services[].state == 'running' "

仅当我使用列表时,我才能设法列出它们:

- name: Running Services 
debug:
msg: "{{ ansible_facts.services[item].state == 'running' }}"
when: "ansible_facts.services[item] is defined and ansible_facts.services[item].state == 'running' "
loop: "{{ inspect_services2 }}"
ignore_errors: yes

最佳答案

简而言之:

---
- name: work with service facts
hosts: localhost

tasks:
- name: gather service facts
service_facts:

- name: show running services
debug:
msg: "{{ ansible_facts.services | dict2items
| selectattr('value.state', '==', 'running') | items2dict }}"

这为您提供了一个包含所有正在运行的服务的所有信息的字典。如果例如您只想显示这些服务的名称,您可以将调试任务中的消息更改为:

        msg: "{{ ansible_facts.services | dict2items 
| selectattr('value.state', '==', 'running') | map(attribute='key') }}"

您当然可以完全自由地使用该结果并将其作为别名放入变量中以重用它。下面是一个无用但实用的示例,在目标服务器上创建一个带有服务名称的文件,只是为了说明:

---
- name: Work with service facts II
hosts: localhost

vars:
# Note1: this will be undefined until service facts are gathered
# Note2: this time this var will be a list of all dicts
# dropping the initial key wich is identical to `name`
running_services: "{{ ansible_facts.services | dict2items
| selectattr('value.state', '==', 'running') | map(attribute='value') }}"

tasks:
- name: gather service facts
service_facts:

- name: useless task creating a file with service name in tmp
copy:
content: "ho yeah. {{ item.name }} is running"
dest: "/tmp/{{ item.name }}.txt"
loop: "{{ running_services }}"

关于ansible - 如何使用 ansible_facts 仅列出正在运行的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70803827/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com