How can we place condition on including recipe on run time while checking windows services on node


#1

how can we place condition on including recipe on run time while checking windows services on node i did some poc. code is given below but things are not working. :frowning_face:

ruby_block ‘Include at run time’ do
block do

run_context.include_recipe ‘sqlserver::install’
#not_if 'sc #{service_name} | find “RUNNING”'
not_if 'sc query state= all | findstr /C:“SERVICE_NAME: #{service_name}”'
end

not_if ‘sc #{service_name} | find “RUNNING”’ = true
#sc query state= all | findstr /C:“SERVICE_NAME: MyService”

end


#2

First develop and test your logic of detecting that target service is running , separately. Chef has shellout (Mixlib::Shellout) helpers to cleanly execute commands, or use proctable gem. You should search for windows specific libraries as well, I am not too familiar with them, but they might be safer and more elegant

require 'sys/proctable'

module ServiceDetector
  include Sys
  def is_running? 
    ProcTable.ps{ |proc_struct|
        # detection code
    }
  end
end

Then move this logic to a dedicated module, lets say its ServiceDetector, and then include it in your chef recipe and use the method as guard clause

# inside recipe
extend ServiceDetector
file '/foo/bar' do
  not_if{ is_running?}
end

#3

i tried to place a include recipe method with in a resource as you suggested and resource will skip if condition not met i tried in the same way but things are not working as before. code reference below-

ruby_block ‘Include at run time’ do
block do

run_context.include_recipe ‘sqlserver::install’

not_if 'sc query state= all | findstr /C:"SERVICE_NAME: #{service_name}"'

end