3

How do I check the status of a Linux service from a chef recipe? Here is my scenario:

  • I would want to perform a bunch of steps only if the service isn't running.

I would like to store the status of the service in a variable(if that is possible), so I can check the value of the variable and proceed accordingly.

Edit:

To elaborate what I am trying to accomplish.

  • I have to install my application as a linux service from chef.
  • But, before I install the service, I want to check if the service is already running in the machine.
  • In Linux terminal, I would use the command

    service myservice status.

  • If the service is not installed the command will return

    myservice: unrecognized service

  • If it is installed and running, it will return

    run.sh (pid 10777) is running...

I would like to determine the status of myservice before I proceed with the installation in the chef recipe.

Maximus
  • 559
  • 1
  • 5
  • 19
  • I don't understand the question. Mind rewriting this or going into more detail? I think an example would help. – Musicode Aug 22 '14 at 16:13

1 Answers1

5

You could create a simple helper like this:

module MyServiceChecker
  def my_service_running?
    cmd = Mixlib::ShellOut.new('/etc/init.d/my_service status')
    cmd.run_command
    cmd.exitstatus == 0
  end
end

Chef::Recipe.send(:include, MyServiceChecker)
Chef::Resource.send(:include, MyServiceChecker)
Chef::Provider.send(:include, MyServiceChecker)

And then use this helper when you want to check if the service is running. Depending on your service and Linux derivative, the command may be different.

sethvargo
  • 26,739
  • 10
  • 86
  • 156