繁体   English   中英

如何使用 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: 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 }}"

要仅列出正在运行的服务,只需

- name: Loop over all services and print name
  debug:
    msg: "{{ item }}"
  when:
    - ansible_facts.services[item].state == 'running'
  with_items: "{{ ansible_facts.services }}"

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM