如何仅列出具有 ansible_facts 的 运行 服务

How to list only the running services with ansible_facts

如何在不提供像第一个代码那样的列表的情况下用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: Loop over all services and print name
  debug:
    msg: "{{ item }}"
  when:
    - ansible_facts.services[item].state == 'running'
  with_items: "{{ ansible_facts.services }}"

感谢

简而言之:

---
- 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 }}"