How to stop and disable services on boot on Linux remote hosts with Ansible?

I'm going to show you a live Playbook with some simple Ansible code.

I'm Luca Berton and welcome to today's episode of Ansible Pilot.

Ansible enable services on boot on remote hosts

  • ansible.builtin.service_facts
  • Return service state information as fact data
  • ansible.builtin.service
  • Manage services

Today we're talking about Ansible modules service_facts and service.

First, you need to acquire the information of the services on the target machine.

This task is performed by the Ansible module service_facts. You can't enable a service that doesn't exist, can you?

The effective actions are performed by the Ansible module service.

The full name is ansible.builtin.service which means that both these modules are part of the collection of modules "builtin" with Ansible and shipped with it.

This module is pretty stable and out for years and its purpose is to manage services on remote hosts.

For Windows targets, use the ansible.windows.win_service module instead.

Parameters

  • name path - name of the service
  • state string - started / stopped / restarted / reloaded
  • enabled boolean - no/yes
  • arguments/args string - extra args

The parameter list is pretty wide but I'll summarize the most useful.

The only required parameter is "name" that specifies the name of the service.

At least one between the "state" and "enabled" parameters is mandatory.

The "state" parameter defines the action that we are going to take.

It has four alternative options:

"started" and "stopped" options allow you to run or stop the service.

"restarted" is a combination of stop and start - you could also customize the number of seconds between using the "sleep" parameter

The "reloaded" option is useful if the service needs to reload the configuration file.

The "enable" parameter allows you to decide if the service should start on boot or not.

The "arguments or args" parameter allows you to specify some additional arguments provided on the command line.

## Playbook

Stop and disable services on boot on Linux remote hosts with Ansible Playbook. Included code and Playbook with chronyd.service NTP server on a RedHat Enterprise Linux 8.

code

  • service_stop_disable_on_boot.yml

``yaml

---

  • name: service module Playbook

hosts: all

become: true

vars:

disable_services:

- "chronyd.service"

tasks:

- name: populate service facts

ansible.builtin.service_facts:

- name: disable services

ansible.builtin.service:

name: "{{ item }}"

enabled: false

state: stopped

when: "item in services"

with_items: '{{ disable_services }}'

`

execution

``bash

$ ansible-playbook -i virtualmachines/demo/inventory services/service_stop_disable.yml

PLAY [service module Playbook] **

TASK [Gathering Facts]