Home > Blockchain >  How to declare a variable for service_facts
How to declare a variable for service_facts

Time:10-07

Below is the sample ansible playbook I use to check the service status using service_facts module and it worked well. Here I need support to define the service name as variable, but when I define it is giving error, VARIABLE NOT DEFINED:

---
- name: Check service status
  hosts: all
  gather_facts: no
  tasks:
    - name: Service Facts
      service_facts:

    - debug:
        var: ansible_facts.services['firewalld.service']['status']

I need "firewalld.service" to be declared under vars section below tasks, tried various options but it is not giving the expected output. I tried below option but it is not working.

---
- name: Check service status
  hosts: all
  gather_facts: no
  vars:
    - SERVICE: firewalld.service
  tasks:
    - name: Service Facts
      service_facts:

    - debug:
        var: ansible_facts.services[SERVICE]['status']

CodePudding user response:

You can run some tasks using conditionals, for example:

    - name: Get service_facts
    service_facts:

    - name: Open some port
    firewalld:
        port: "{{ some_port }}/tcp"
        permanent: yes
        immediate: yes
        offline: no
        state: enabled
    when: 
        - ansible_facts.services['firewalld.service'].state == 'running'
        - ansible_facts.services['firewalld.service'].status == 'enabled'

CodePudding user response:

A specific service can be available under service_facts only if it exists. If you like to perform tasks on a service of which you don't know if it is there the already mentioned Conditionals may work.

- name: Gathering Service Facts
  service_facts:
  tags: remove,stop,disable

- name: Make sure {{ SERVICE }} is stopped and disabled
  systemd:
    name: {{ SERVICE }}
    state: stopped
    enabled: no
  when: ("{{ SERVICE }}" in services)
  tags: remove,stop,disable

- name: Make sure {{ SERVICE }} is removed
  yum:
    name: {{ SERVICE }}
    state: absent
  tags: remove
  • Related