I am trying to provision windows server 2012 R2 machine with ansible and for that i need to gather some custom facts about the running services. I tried getting the information via the win_service module like this:
I suggest you add a task, before your win_service task that installs the service if it is not yet installed. Depending on what the service is, you might be able to use win_package to install it. If it is already installed, there is not much to loose by running the win_package task a second time, as it will only install if not installed.
When provisioning, I like to write playbooks that drag the machine into the state that I want it in rather than trying to write playbooks that have to handle lots of different possiblities that might exist on the different machines.
Hope this helps,
Jon
Agreed with your point - we should drag the machine in the state we want. But in my case the number 1 priority is to make the script idempotent, which seems like quite a thing on windows end.
I not installing anything on the windows end and my application will run as standalone service, no installation required. I am using NSSM to install the services, so win_package is not going to be of any use to me.
To make my script idempotent, i must first check if the service exists, before i invoke NSSM to create the service. I can live with the complicated conditionals i will have in my scripts, but they must be idempotent in the end.
The solution where i check the service with win_service works fine except that in the case it is not present, it will give me a lot of red statements. What i am looking for is a better way where i can simply check that if a given service is created or not. I wish NSSM had some API to check for that.
You could run a raw powershell command like
Get-Service nameOfService -ErrorAction SilentlyContinue
and then register the result, then check
You would need the ‘-ErrorAction SilentlyContinue’ bit otherwise when the service doesn’t exist, Get-Service will fail.
also if you prefer you could do something similar with the sc.exe like this
sc.exe query serviceName
Hope this helps.
Both get-service and sc.exe returns textual results. I will have to match strings to check if service exists and its state and i never like to base my conditions on pattern matching.
The best solution i could thing of is to go with win_service and define a failed_when situation along with. At least i will have the results in proper json objects.
win_service returns values such as exists(which is false or true depending whether the service is absent or present).So you can just use something like
{when: win_service_register.exists} to any task which u want to execute only if the service is present. .