Ansible uses modules to accomplish most of its tasks. One of these modules is win_service which is designed explicitly for managing the Windows services.
This post walks you through the workings of this module and provide examples on how to use it in real-world playbooks.
Requirements:
To follow along with this post and the provided examples, ensure that you have the following:
- Anisble controller node
- A Windows host that you wish to manage
- The Windows host(s) must be set up for WinRM communication
Installing the Windows Collection
The win_service module is part of the “ansible.windows” collection. Therefore, we need to ensure that we have it installed before use. We can run the command as follows:
Ansible Win_Service Module
The win_service module in Ansible enables us to start, stop, and configure the Windows services. With this module, we can easily automate the Windows service management, ensuring that services are consistent across multiple servers.
Example Usage:
Let us explore the various examples on how to use this module.
Example 1: Get the Service Info
The first primary usage is to fetch the details of a Windows service as demonstrated in the following playbook example :
- name: Get information about a service
hosts: windows
tasks:
- name: Get details for IIS Server
ansible.windows.win_service:
name: W3SVC
register: service_info
- name: Display service information
debug:
var: service_info
Example 2: Start a Service
To start a service using the win_service module, run the playbook as follows:
- name: Start IIS Server
hosts: windows
tasks:
- name: Ensure W3SVC service is started
ansible.windows.win_service:
name: W3SVC
state: started
Example 3: Stop a Service
To stop a service, use the state parameter as follows:
- name: Stop IIS Server
hosts: windows
tasks:
- name: Ensure W3SVC service is stopped
ansible.windows.win_service:
name: W3SVC
state: stopped
Example 4: Change the User Account of a Service
We can also change the user account under which a service runs by providing the username and password parameters as shown in the following example:
- name: Change service user account
hosts: windows
tasks:
- name: Change W3SVC service user account
ansible.windows.win_service:
name: W3SVC
username: DOMAIN\Administrator
password: password
Example 5: Pause a Service
We can also pause a running service by setting the status to “paused” as demonstrated in the following:
- name: Pause a service
hosts: windows
- tasks:
- name: pause IIS
ansible.windows.win_service:
name: W3SVC
state: paused
Example 6: Set the Service Dependencies
If you want to ensure that a service has specific dependencies, you can specify them as follows:
- name: Set service dependencies
hosts: windows_host
tasks:
- name: Set W3SVC service dependencies
ansible.windows.win_service:
name: W3SVC
dependencies:
- dns
- MySQL80
Conclusion
You learned how to use the win_service module in Ansible to get a powerful way to manage and configure the Windows services.