Jake
Jake

Reputation: 13151

Chef - start OR restart service as needed

With Chef, how can I have a service start if it's not running or restart if it is?

I'm running Ubuntu 12.04 and the service I'm currently dealing with is PostgreSQL. Stopping and starting it almost works but Chef seems to try starting it before it's stopped fully and fail.

Upvotes: 7

Views: 8004

Answers (2)

Andy
Andy

Reputation: 4866

Here's an outline of the code I used to conditionally perform one of several (re)start type actions for a docker container. It could be adapted for the service (re)start situation in a case where the always restart advice from @giannis-nohj doesn't work for some reason.

my_file = file ...

my_image = docker_image 'my-image' do
  repo 'my-image'
  action :pull
end

ruby_block 'compute docker action' do
  block do
    action = if my_image.updated_by_last_action?
      :redeploy
    elsif my_file.updated_by_last_action?
      :restart
    else
      :run
    end
    resources('docker_container[my-container]').delayed_action(action)
  end
end

docker_container 'my-container' do
  repo 'my-image'
  action :nothing
end

Upvotes: 0

StephenKing
StephenKing

Reputation: 37630

Usually, you use action :start when installing a service to make sure it's running after the chef run, see Service resource.

When you modify a file that requires the service to restart in order to make the changes active, you use the actions :reload or :restart (dependent on what the init script offers). It then looks like this:

template "/etc/postgresql/pg.conf" do
  source "pg.conf.erb"
  notifies :restart, "service[postgres]"
end

More about Notifications.

Upvotes: 3

Related Questions