'Ansible: How to start stopped services?

I created a playbook that uses ansible_facts.services to restart specific services on multiple RHEL servers. The services that get restarted begin with a specific name and may or may not exist on the different hosts where the playbook is ran.

I have this working correctly but I would also like to add a follow up task that checks the services that were restarted in the previous task to make sure they are running. The task would need to only check the services that were restarted then start the service if the status is stopped.

Please recommend the best way to do this. Include code if possible. Thanks!



Solution 1:[1]

It's sounds odd, but you may try to use handlers (to react on 'changes') and use check_mode for the module to assure the state.

Try to add 'notify' to the restarting task, and check_mode: true to the handler. Handler is, basically, the same systemd module, but without ability to change.

... Or, if you want to test your infrastructure, may be you may like testinfra (pytest-testinfra) as a tool to check your infra.

Solution 2:[2]

I understand your question that you like to make sure that a list of serivces is running.

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

Based on that example you could start the service if the status is stopped.

Further Q&A

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 George Shuklin
Solution 2