service resource

[edit on GitHub]

Use the service resource to manage a service.

Syntax

The service resource has the following syntax:

service "tomcat" do
  action :start
end

will start the Apache Tomcat service.

The full syntax for all of the properties that are available to the service resource is:

service 'name' do
  init_command               String
  notifies                   # see description
  options                    Array, String
  pattern                    String
  priority                   Integer, String, Hash
  reload_command             String
  restart_command            String
  service_name               String # defaults to 'name' if not specified
  start_command              String
  status_command             String
  stop_command               String
  subscribes                 # see description
  supports                   Hash
  timeout                    Integer # Microsoft Windows only
  action                     Symbol # defaults to :nothing if not specified
end

where

  • service is the resource
  • name is the name of the resource block; when the path property is not specified, name is also the path to the directory, from the root
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • init_command, options, pattern, priority, reload_command, restart_command, service_name, start_command, status_command, stop_command, supports, and timeout are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions

The service resource has the following actions:

:disable
Disable a service. This action is equivalent to a Disabled startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot.
:enable
Enable a service at boot. This action is equivalent to an Automatic startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot.
:nothing
Default. Do nothing with a service.
:reload
Reload the configuration for this service.
:restart
Restart a service.
:start
Start a service, and keep it running until stopped or disabled.
:stop
Stop a service.

Note

To manage a Microsoft Windows service with a Manual startup type, the windows_service resource must be used.

Properties

The service resource has the following properties:

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

init_command

Ruby Type: String

The path to the init script that is associated with the service. Use init_command to prevent the need to specify overrides for the start_command, stop_command, and restart_command properties. When this property is not specified, the chef-client will use the default init command for the service provider being used.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

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.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
options

Ruby Type: Array, String

Solaris platform only. Options to pass to the service command. See the svcadm manual for details of possible options.

pattern

Ruby Type: String | Default Value: service_name

The pattern to look for in the process table.

priority

Ruby Type: Integer, String, Hash

Debian platform only. The relative priority of the program for start and shutdown ordering. May be an integer or a Hash. An integer is used to define the start run levels; stop run levels are then 100-integer. A Hash is used to define values for specific run levels. For example, { 2 => [:start, 20], 3 => [:stop, 55] } will set a priority of twenty for run level two and a priority of fifty-five for run level three.

reload_command

Ruby Type: String

The command used to tell a service to reload its configuration.

restart_command

Ruby Type: String

The command used to restart a service.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

service_name

Ruby Type: String

The name of the service. Default value: the name of the resource block. See “Syntax” section above for more information.

start_command

Ruby Type: String

The command used to start a service.

status_command

Ruby Type: String

The command used to check the run status for a service.

stop_command

Ruby Type: String

The command used to stop a service.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

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:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

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.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
supports

Ruby Type: Hash

A list of properties that controls how the chef-client is to attempt to manage a service: :restart, :reload, :status. For :restart, the init script or other service provider can use a restart command; if :restart is not specified, the chef-client attempts to stop and then start a service. For :reload, the init script or other service provider can use a reload command. For :status, the init script or other service provider can use a status command to determine if the service is running; if :status is not specified, the chef-client attempts to match the service_name against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: { restart: false, reload: false, status: false } for all platforms (except for the Red Hat platform family, which defaults to { restart: false, reload: false, status: true }.)

timeout

Ruby Type: Integer | Default Value: 60

Microsoft Windows platform only. The amount of time (in seconds) to wait before timing out.

Examples

The following examples demonstrate various approaches for using resources in recipes. If you want to see examples of how Chef uses resources in recipes, take a closer look at the cookbooks that Chef authors and maintains: https://github.com/chef-cookbooks.

Start a service

service 'example_service' do
  action :start
end

Start a service, enable it

service 'example_service' do
  supports :status => true, :restart => true, :reload => true
  action [ :enable, :start ]
end

Use a pattern

service 'samba' do
  pattern 'smbd'
  action [:enable, :start]
end

Use the :nothing common action

service 'memcached' do
  action :nothing
end

Use the retries common attribute

service 'apache' do
  action [ :enable, :start ]
  retries 3
end

Manage a service, depending on the node platform

service 'example_service' do
  case node['platform']
  when 'centos','redhat','fedora'
    service_name 'redhat_name'
  else
    service_name 'other_name'
  end
  supports :restart => true
  action [ :enable, :start ]
end

Change a service provider, depending on the node platform

service 'example_service' do
  case node['platform']
  when 'ubuntu'
    if node['platform_version'].to_f >= 9.10
      provider Chef::Provider::Service::Upstart
    end
  end
  action [:enable, :start]
end

Reload a service using a template

To reload a service that is based on a template, use the template and service resources together in the same recipe, similar to the following:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
end

service 'apache' do
  action :enable
  subscribes :reload, 'template[/tmp/somefile]', :immediately
end

where the subscribes notification is used to reload the service whenever the template is modified.

Enable a service after a restart or reload

service 'apache' do
  supports :restart => true, :reload => true
  action :enable
end

Set an IP address using variables and a template

The following example shows how the template resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following:

default['nginx']['dir'] = '/etc/nginx'

The recipe then does the following to:

  • Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address
  • Use the service resource to restart and reload the Nginx service
  • Load a template named authorized_ip.erb from the /templates directory that is used to set the IP address values based on the variables specified in the recipe
node.default['nginx']['remote_ip_var'] = 'remote_addr'
node.default['nginx']['authorized_ips'] = ['127.0.0.1/32']

service 'nginx' do
  supports :status => true, :restart => true, :reload => true
end

template 'authorized_ip' do
  path "#{node['nginx']['dir']}/authorized_ip"
  source 'modules/authorized_ip.erb'
  owner 'root'
  group 'root'
  mode '0755'
  variables(
    :remote_ip_var => node['nginx']['remote_ip_var'],
    :authorized_ips => node['nginx']['authorized_ips']
  )

  notifies :reload, 'service[nginx]', :immediately
end

where the variables property tells the template to use the variables set at the beginning of the recipe and the source property is used to call a template file located in the cookbook’s /templates directory. The template file looks similar to:

geo $<%= @remote_ip_var %> $authorized_ip {
  default no;
  <% @authorized_ips.each do |ip| %>
  <%= "#{ip} yes;" %>
  <% end %>
}

Use a cron timer to manage a service

The following example shows how to install the crond application using two resources and a variable:

# the following code sample comes from the ``cron`` cookbook:
# https://github.com/chef-cookbooks/cron

cron_package = case node['platform']
  when 'redhat', 'centos', 'scientific', 'fedora', 'amazon'
    node['platform_version'].to_f >= 6.0 ? 'cronie' : 'vixie-cron'
  else
    'cron'
  end

package cron_package do
  action :install
end

service 'crond' do
  case node['platform']
  when 'redhat', 'centos', 'scientific', 'fedora', 'amazon'
    service_name 'crond'
  when 'debian', 'ubuntu', 'suse'
    service_name 'cron'
  end
  action [:start, :enable]
end

where

  • cron_package is a variable that is used to identify which platforms apply to which install packages
  • the package resource uses the cron_package variable to determine how to install the crond application on various nodes (with various platforms)
  • the service resource enables the crond application on nodes that have Red Hat, CentOS, Red Hat Enterprise Linux, Fedora, or Amazon Web Services (AWS), and the cron service on nodes that run Debian, Ubuntu, or openSUSE

Restart a service, and then notify a different service

The following example shows how start a service named example_service and immediately notify the Nginx service to restart.

service 'example_service' do
  action :start
  notifies :restart, 'service[nginx]', :immediately
end

Restart one service before restarting another

This example uses the :before notification to restart the php-fpm service before restarting nginx:

service 'nginx' do
  action :restart
  notifies :restart, 'service[php-fpm]', :before
end

With the :before notification, the action specified for the nginx resource will not run until action has been taken on the notified resource (php-fpm).

Stop a service, do stuff, and then restart it

The following example shows how to use the execute, service, and mount resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following:

  • Checks to see if the Amazon EC2 node has MySQL
  • If the node has MySQL, stops MySQL
  • Installs MySQL
  • Mounts the node
  • Restarts MySQL
# the following code sample comes from the ``server_ec2``
# recipe in the following cookbook:
# https://github.com/chef-cookbooks/mysql

if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path']))

  service 'mysql' do
    action :stop
  end

  execute 'install-mysql' do
    command "mv #{node['mysql']['data_dir']} #{node['mysql']['ec2_path']}"
    not_if do FileTest.directory?(node['mysql']['ec2_path']) end
  end

  [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir|
    directory dir do
      owner 'mysql'
      group 'mysql'
    end
  end

  mount node['mysql']['data_dir'] do
    device node['mysql']['ec2_path']
    fstype 'none'
    options 'bind,rw'
    action [:mount, :enable]
  end

  service 'mysql' do
    action :start
  end

end

where

  • the two service resources are used to stop, and then restart the MySQL service
  • the execute resource is used to install MySQL
  • the mount resource is used to mount the node and enable MySQL

Control a service using the execute resource

Warning

This is an example of something that should NOT be done. Use the service resource to control a service, not the execute resource.

Do something like this:

service 'tomcat' do
  action :start
end

and NOT something like this:

execute 'start-tomcat' do
  command '/etc/init.d/tomcat6 start'
  action :run
end

There is no reason to use the execute resource to control a service because the service resource exposes the start_command property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner.

Enable a service on AIX using the mkitab command

The service resource does not support using the :enable and :disable actions with resources that are managed using System Resource Controller (SRC). This is because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot.

One approach for enabling or disabling services that are managed by System Resource Controller (SRC) is to use the execute resource to invoke mkitab, and then use that command to enable or disable the service.

The following example shows how to install a service:

execute "install #{node['chef_client']['svc_name']} in SRC" do
  command "mkssys -s #{node['chef_client']['svc_name']}
                  -p #{node['chef_client']['bin']}
                  -u root
                  -S
                  -n 15
                  -f 9
                  -o #{node['chef_client']['log_dir']}/client.log
                  -e #{node['chef_client']['log_dir']}/client.log -a '
                  -i #{node['chef_client']['interval']}
                  -s #{node['chef_client']['splay']}'"
  not_if "lssrc -s #{node['chef_client']['svc_name']}"
  action :run
end

and then enable it using the mkitab command:

execute "enable #{node['chef_client']['svc_name']}" do
  command "mkitab '#{node['chef_client']['svc_name']}:2:once:/usr/bin/startsrc
                  -s #{node['chef_client']['svc_name']} > /dev/console 2>&1'"
  not_if "lsitab #{node['chef_client']['svc_name']}"
end