How to ensure a service is running, using Chef?

By default, Chef will check if the service is running, and starts it if the service isn't running.

How it determines that the service is running depends.

By default, Chef will attempt to match the name of the service (postgresql here) in the process table using ps.

ps -ef | grep postgresql

Essentially. The name of the service will be used for the pattern match when inspecting the process table. This may or may not be what you want/need, especially depending on the platform and how it names the "postgresql" service.

However, you can tell Chef that the service supports a "status" command, which means Chef will generally do something like,

/etc/init.d/postgresql status

And use the return code to determine if it's running or not (non-zero is not running).

Chef doesn't do this by default because not all service scripts support a status command (frustratingly), and Chef doesn't innately know what the right thing to do is. It tries to do the sane default thing, but sometimes naïve. Thus, you can tell Chef that the resource has a status command and not be so naïve.

service "postgresql" do
  supports :status => true
  action :start
end

Now, if the service is not actually named "postgresql" but is instead "postgresql-92" or similar, you can do this as:

service "postgresql-92" do
  supports :status => true
  action :start
end

or

service "postgresql" do
  service_name "postgresql-92"
  supports :status => true
  action :start
end

You can find out what's going on in more detail by running chef with debug output, too:

chef-client -l debug