A collection of task oriented solutions in Puppet

 

Restart a service when a file changes

Challenge

You want to restart a service when its config file changes

Solution

class ssh {

  service { 'sshd':
    ensure  => 'running',
    enable  => true,
    require => Package['openssh-server'],
  }

  # add a notify to the file resource
  file { '/etc/ssh/sshd_config':
    notify  => Service['sshd'],  # this sets up the relationship
    mode    => '0600',
    owner   => 'root',
    group   => 'root',
    require => Package['openssh-server'],
    content => template('ssh/sshd_config.erb'),
  }

}

Explanation

It would be very annoying if puppet allowed you to deploy a new config file without providing a way to restart a service to take advantage of the change. Using the notify metaparameter we can tell a resource to signal another resource, often a file notifying a service, and cause it to refresh, which in the case of a service causes a restart.

Puppet will accumulate multiple notifies over a single run and only refresh the service once. This is useful for services like Nagios where a large number of config files can change for one amendment and nothing would be gained from multiple restarts.

It's worth noting that you probably don't want to use this with larger, more important, services like MySQL where a small white space change in a config file could cause a restart of your MySQL database and begin a domino effect of application issues.

See also