Notifications and subscriptions in Chef

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:
  • :before - means, go ahead and notify this particular resource to take action before my actual resource that I'm embedded inside of
  • :delayed - execute the resource that I'm inside of and then send a notification
  • :immediately - run as quickly as possible

Example of notifications:
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]

We can also go in the opposite direction, instead of notifies we also have subscribes:
subscribes :action, 'resource[name]', :timer
we can actually listen to another resource and then take action

Example of subscription:
template '/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]