Chef: How do I check to see if a service is installed?
Asked Answered
C

1

6

In a recipe I want to check to see if a service is installed, and if it is not notify the 3 resources needed to install it. I tried the service resource, which correctly identifies the service when it is installed, but throws an exception if the service is not installed.

I'm not sure what action to use here. :nothing just skips the resource so it ever get executed, but any of the other actions will error when they attempt to act on a service that doesn't exist.

How do I detect whether a service is installed and act based on that information?

I'm running on Windows, if that's relevant.

Cobbs answered 21/11, 2013 at 20:59 Comment(0)
R
10

Take a look on how is service for windows is defined

https://github.com/opscode/chef/blob/master/lib/chef/provider/service/windows.rb

AFAIU its pretty straighforward add import to your recipe:

require 'win32/service'

and then you can check if service exists with

Win32::Service.exists?(@new_resource.service_name)

voila - you can put impementation to library (http://docs.opscode.com/essentials_cookbook_libraries.html) just not to pollute recipe code and have simple method service_exists?.

Rozina answered 22/11, 2013 at 8:24 Comment(3)
This got me on the right track. I got it working without the require statement. Per this mailing list entry: lists.opscode.com/sympa/arc/chef/2013-03/msg00223.html the statement if !::Win32::Service.exists?("test_service_name") correctly detects whether the service exists. The leading :: tell it not to look in the Chef namespace.Cobbs
@Rozina can you please add the syntax from CPS's comment?Cantilever
The preceding :: won it for me - this saved me a lot of time. Thank youAntagonistic

© 2022 - 2024 — McMap. All rights reserved.