I am trying to build a kind of self contained system where i copy my application executables in a place and run the services as standalone applications, no installations. I am using NSSM executable to create services in windows server 2012 R2 and on one machine, there are going to be a lot of deployables. My problem is that while automating the deployment with Ansible, i am stuck at the point where i need to know if a given service name already exists and if yes, what is its state ? There don't seem to be any API in NSSM to check that. How can i ask NSSM via command line that if a service exists ? Can i check the existence and status of a service via command line (no powershell) ?
Well there is no way to get service details only via NSSM so i figured out a few other ways to get a windows service details in ansible:
1) Using sc.exe command util sc utility can query the windows machine to get details about the given service name. We can register the results of this query in variable and use it in other tasks in conditions.
---
- hosts: windows
tasks:
- name: Check if the service exists
raw: cmd /c sc query serviceName
register: result
- debug: msg="{{result}}"
2) Using Get-Service Powershell command 'Get-Service' can give you the details about the service just like sc util:
---
- hosts: windows
tasks:
- name: Check if the service exists
raw: Get-Service serviceName -ErrorAction SilentlyContinue
register: result
- debug: msg="{{result}}"
3) win_service module (recommended) Ansible's module win_service can be used to simply get service details by not specifying any action. The only problem is the case when service does not exist where it will fail the task. That can be countered using failed_when or ignore_errors.
---
- hosts: windows
tasks:
- name: check services
win_service:
name: serviceName
register: result
failed_when: result is not defined
#ignore_errors: yes
- debug: msg="{{result}}"
- debug: msg="running"
when: result.state is not defined or result.name is not defined