Anass JARBAL
Anass JARBAL

Reputation: 1

Ansible - check if service exists, then execute tasks

I have an Ansible playbook which allows listing services (Postgres, ElasticSearch, MongoDB, MySQL) and their versions installed on the machines.

I would like to add a condition which skips the task if the service does not exist.

I tried the following, but it does not work:

when: "'postgresql.service' in services"

I configured this is task to scan for services:

tasks:
  - name: Gather services
    service_facts:
    become: true
  - name: Filter services
    set_fact:
      services_app: "{{ services | dict2items
        | selectattr('value.state', 'match', 'running')
        | selectattr('value.source', 'match', service_mgr | string)
        | selectattr('value.name', 'search', (services_to_scan | join('|')))
        | map(attribute='key') | list | default([]) }}"

And this is the task to scan for postgresql.service:

- name: Check Postgresql
  shell: psql --version
  register: psql

- name: debbuger la version Postgres
  debug: var=psql.stdout_lines
  when: "'postgresql.service' in services"

Upvotes: 0

Views: 1780

Answers (1)

Kevin C
Kevin C

Reputation: 5740

You almost got it, first you need to populate the services list.

- name: Populate service facts
  ansible.builtin.service_facts:

- name: retrieve postgresql version when service is available
  shell: psql --version
  when: "'postgresql.service' in services"

Upvotes: 3

Related Questions