Running a command when a file is updated
If your node is not under complete Chef control, it might be necessary to trigger commands when Chef changes a file. For example, you might want to restart a service that is not managed by Chef when its configuration file (which is managed by Chef) changes. Let's see how you can achieve this with Chef.
Getting ready
Make sure that you have a cookbook called my_cookbook
and that the run_list
of your node includes my_cookbook
, as described in the Creating and using cookbooks recipe in Chapter 1, Chef Infrastructure.
How to do it...
Let's create an empty file as a trigger and run a bash
command, if that file changes:
Edit your cookbook's default recipe:
mma@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb template "/tmp/trigger" do notifies :run, "bash[run_on_trigger]", :immediately end bash "run_on_trigger" do user "root" cwd "/tmp" code "echo 'Triggered'" action :nothing end
Create an empty template:
mma@laptop:~/chef-repo ...