Chef notifies and subscribes explained with examples
A notification is a property on a resource that listens to other resources in the resource collection and then takes actions based on the notification type (notifies or subscribes).
A timer specifies the point during the chef-client run at which a notification is run. The following timers are available:
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
Default. Specifies that a notification should be queued up, and then executed at the very end of the chef-client run.
Specifies that a notification should be run immediately, per resource notified.
A resource may notify another resource to take action when its state changes. Specify a ‘resource[name]’, the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.
The syntax for notifies is:
notifies :action, ‘resource[name]’, :timer
The following examples show how to use the notifies notification in a recipe.
and then the chef-client would immediately run the following:
execute ‘test-nagios-config’ do
command ‘nagios3 –verify-config’
A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a ‘resource[name]’, the :action to be taken, and then the :timer for that action.
Note that subscribes does not apply the specified action to the resource that it listens to – for example:
In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.
The syntax for subscribes is:
subscribes :action, ‘resource[name]’, :timer
The following examples show how to use the subscribes notification in a recipe.
Prevent restart and reconfigure if configuration is broken
Use the :nothing action (common to all resources) to prevent the test from starting automatically, and then use the subscribes notification to run a configuration test when a change to the template is detected: