Chef stop and start service in sequence
I have the following lines in my recipe
service "apache" do
action :stop
end
# Do something..
service "apache" do
action :start
end
I found that the 2nd block is not executed. Any reason?
Solution 1:
Notifications are the right way to handle this.
Suppose you want to do the following:
- Conditionally download a file
- If the file is downloaded
- Stop apache immediately
- Process the file (e.g. unzip it or move it)
- Start apache again
You would do it like this:
# Define the apache service but don't do anything with it
service "apache" do
action :nothing
end
# Define your post-fetch script but don't actually do it
execute "process my file" do
... your code here
action :nothing
notifies :start, "service[apache]"
end
# Fetch the file. Maybe the file won't be fetched because of not_if or checksum.
# In that case apache won't be stopped or started, it will just keep running.
remote_file "/tmp/myfile" do
source "http://fileserver/myfile"
notifies :stop, "service[apache]", :immediately
notifies :run, execute["process my file"]
end
Solution 2:
The problem is that your resources have the same name. service "apache" is not unique, so chef is de-duplicating them. Your options are to give them separate names like this
service "apache stop" do
service_name "apache"
action :stop
end
# Do something
service "apache start" do
service_name "apache"
action :start
end
you could also use a notification from the "# Do something" block to send a :restart to the service "apache". That's the usual pattern people use, a single service, sending it notifications (or using subscribes). More here:
http://wiki.opscode.com/display/chef/Resources#Resources-Notifications
Solution 3:
Mray's and kgilpin's answers are perfect, but I ran into problems recently.
Somehow mysql service didn't stop before I needed to restart it and thus my recipe failed. I used workaround using '''Execute''' resource (I need recipes working on Ubuntu only). Execute is waiting for stop/start, while service could end earlier (init script will finish, while daemon not)
execute "Stop service" do command "service stop" end
I not proud for this solution, but it is working for me.
Solution 4:
To add to this;
Chef does not start a service unless /etc/init.d/<DAEMON> status
returns something other than 0. If it returns 0 then chef assumes that it's running.