Viktor Saienko
Viktor Saienko

Reputation: 101

Ansible 2.5 Module "service_facts". How can filter an output? How can get as result not all services, only some services or one service?

If we use this module "service_facts" how in manual we will get as result all running services. The output result is output in JSON format like as below (this a part of result)

{    
    "ansible_facts.services": {
        "rsyslog": {
            "name": "rsyslog",
            "source": "sysv",
            "state": "running"
        },
        "rsyslog.service": {
            "name": "rsyslog.service",
            "source": "systemd",
            "state": "running"
        },
        "sendsigs.service": {
            "name": "sendsigs.service",
            "source": "systemd",
            "state": "stopped"
        }      
    }  
}

I newbie in Ansible.

How can filtere an output correctly in Ansible?

Upvotes: 2

Views: 10204

Answers (2)

stevansv
stevansv

Reputation: 15

Maybe you would also be interested in filtering out stopped/running services and assigning them to separate variables in this post:

ansible json filter list

Upvotes: 0

ilias-sp
ilias-sp

Reputation: 6685

I agree, this module creates a single associative array of elements [] => array(), which makes it hard to process in ansible, it would be much better if the [services] element it injects was a list.

Anyway, here is a playbook that will split for you the services to a list variable of running and a list variable of not running (state != "running")

---
- hosts: localhost
  gather_facts: no
  vars:
    newline_character: "\n"
    services_running: []
    services_NOT_running: []
  tasks:
  - name: populate service facts
    service_facts:

  - name: populate running services
    set_fact:
      services_running: "{{ services_running + [item] }}"
    when: hostvars[inventory_hostname]['services']['{{item}}']['state'] == "running"
    with_items: "{{ hostvars[inventory_hostname]['services'].keys() }}"

  - name: populate NOT running services
    set_fact:
      services_NOT_running: "{{ services_NOT_running + [item] }}"
    when: hostvars[inventory_hostname]['services']['{{item}}']['state'] != "running"
    with_items: "{{ hostvars[inventory_hostname]['services'].keys() }}"

  - debug:
      msg: "running services: {{ services_running }}"

  - debug:
      msg: "NOT running services: {{ services_NOT_running }}"

Upvotes: 2

Related Questions