Notifications and subscriptions are properties common to all Chef resources: all resources have the ability to notify or subscribe to another resource if its state changes someway.
This is particular useful for configuration files: for example to change a specific configuration of a service on a disk and then reload the corresponding service that needs that configuration file.
For this we can send a notification:
notifies :action, 'resource[name]', :timer
There are 3 types of timers:
template '/var/www/html/index.html' do
source 'index.html.erb'
variables(:name => "Dmitri-notify")
notifies :restart, 'service[apache2]', :immediately
end
service 'apache2' do
action [:enable, :start ]
end
Output:
* template[/var/www/html/index.html] action create
- update content in file /var/www/html/index.html from 160ee1 to ce8ed4
--- /var/www/html/index.html 2021-01-18 20:20:31.138788451 +0000
+++ /var/www/html/.chef-index20210222-2120-esasqo.html 2021-02-22 20:47:53.184162155 +0000
@@ -1,4 +1,4 @@
-Hello Dmitri
+Hello Dmitri-notify
HOSTNAME: buster
IPADDRESS: 192.168.121.94
<img src='image.png'>
* service[apache2] action restart
- restart service service[apache2]
subscribes :action, 'resource[name]', :timer
we can actually listen to another resource and then take actiontemplate '/var/www/html/index.html' do
source 'index.html.erb'
variables(:name => "Dmitri")
end
service 'apache2' do
action [:enable, :start ]
subscribes :restart, 'template[/var/www/html/index.html]', :immediately
end
Output:
* template[/var/www/html/index.html] action create
- update content in file /var/www/html/index.html from ce8ed4 to 160ee1
--- /var/www/html/index.html 2021-02-22 20:47:53.184162155 +0000
+++ /var/www/html/.chef-index20210222-2687-1j8d863.html 2021-02-22 20:50:55.821208344 +0000
@@ -1,4 +1,4 @@
-Hello Dmitri-notify
+Hello Dmitri
HOSTNAME: buster
IPADDRESS: 192.168.121.94
<img src='image.png'>
* service[apache2] action restart
- restart service service[apache2]