service
Use the service resource to manage a service.
Syntax
A service resource block manages the state of a service. For example:
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 pattern String priority Integer, String, Hash provider Chef::Provider::Service 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
-
serviceis the resource; depending on the platform, more specific providers are run:Chef::Provider::Service::Init,Chef::Provider::Service::Init::Debian,Chef::Provider::Service::Upstart,Chef::Provider::Service::Init::Freebsd,Chef::Provider::Service::Init::Gentoo,Chef::Provider::Service::Init::Redhat,Chef::Provider::Service::Solaris,Chef::Provider::Service::Windows, orChef::Provider::Service::Macosx -
nameis the name of the resource block; when thepathproperty is not specified,nameis also the path to the directory, from the root -
:actionidentifies the steps the chef-client will take to bring the node into the desired state -
init_command,pattern,priority,provider,reload_command,restart_command,service_name,start_command,status_command,stop_command,supports, andtimeoutare 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
This resource has the following actions:
:disable- Disable a service.
:enable- Enable a service at 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.
Properties
This resource has the following properties:
ignore_failure-
Ruby Types: TrueClass, FalseClass
Continue running a recipe if a resource fails for any reason. Default value:
false. init_command-
Ruby Type: String
The path to the init script that is associated with the service. Use
init_commandto prevent the need to specify overrides for thestart_command,stop_command, andrestart_commandproperties. 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:actionthat resource should take, and then the:timerfor that action. A resource may notifiy more than one resource; use anotifiesstatement 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:
:delayed- Default. Specifies that a notification should be queued up, and then executed at the very end of the chef-client run.
-
:immediate,:immediately - Specifies that a notification should be run immediately, per resource notified.
The syntax for
notifiesis:notifies :action, 'resource[name]', :timer
pattern-
Ruby Type: String
The pattern to look for in the process table. Default value:
service_name. priority-
Ruby Types: 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. provider-
Ruby Type: Chef Class
Optional. Explicitly specifies a provider. See “Providers” section below for more information.
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
The number of times to catch exceptions and retry the resource. Default value:
0. retry_delay-
Ruby Type: Integer
The retry delay (in seconds). Default value:
2. service_name-
Ruby Type: String
The name of the service. Default value: the
nameof 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:actionto be taken, and then the:timerfor that action.A timer specifies the point during the chef-client run at which a notification is run. The following timers are available:
:delayed- Default. Specifies that a notification should be queued up, and then executed at the very end of the chef-client run.
-
:immediate,:immediately - Specifies that a notification should be run immediately, per resource notified.
The syntax for
subscribesis: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:restartis 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:statusis not specified, the chef-client attempts to match theservice_nameagainst 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
Microsoft Windows platform only. The amount of time (in seconds) to wait before timing out. Default value:
60.
Providers
Where a resource represents a piece of the system (and its desired state), a provider defines the steps that are needed to bring that piece of the system from its current state into the desired state.
The chef-client will determine the correct provider based on configuration data collected by Ohai at the start of the chef-client run. This configuration data is then mapped to a platform and an associated list of providers.
Generally, it’s best to let the chef-client choose the provider, and this is (by far) the most common approach. However, in some cases, specifying a provider may be desirable. There are two approaches:
- Use a more specific short name—
yum_package "foo" doinstead ofpackage "foo" do,script "foo" doinstead ofbash "foo" do, and so on—when available - Use the
providerproperty within the resource block to specify the long name of the provider as a property of a resource. For example:provider Chef::Provider::Long::Name
The service resource does not have service-specific short names. This is because the chef-client identifies the platform at the start of every chef-client run based on data collected by Ohai. The chef-client looks up the platform in the provider_mapping.rb file, and then determines the correct provider for that platform. In certain situations, such as when more than one init system is available on a node, a specific provider may need to be identified by using the provider attribute and the long name for that provider.
This resource has the following providers:
-
Chef::Provider::Service::Init,service - When this short name is used, the chef-client will determine the correct provider during the chef-client run.
-
Chef::Provider::Service::Init::Debian,service - The provider for the Debian and Ubuntu platforms.
-
Chef::Provider::Service::Upstart,service - The provider that is used when Upstart is available on the platform.
-
Chef::Provider::Service::Init::Freebsd,service - The provider for the FreeBSD platform.
-
Chef::Provider::Service::Init::Gentoo,service - The provider for the Gentoo platform.
-
Chef::Provider::Service::Init::Redhat,service - The provider for the Red Hat and CentOS platforms.
-
Chef::Provider::Service::Solaris,service - The provider for the Solaris platform.
-
Chef::Provider::Service::Windows,service - The provider for the Microsoft Windows platform.
-
Chef::Provider::Service::Macosx,service - The provider for the Mac OS X platform.
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 supports :status => true, :start => true, :stop => true, :restart => true end
Use the supports common attribute
service 'apache' do supports :restart => true, :reload => true action :enable end
Use the supports and providers common attributes
service 'some_service' do provider Chef::Provider::Service::Upstart supports :status => true, :restart => true, :reload => true action [ :enable, :start ] 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 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 supports :restart => true, :reload => true action :enable subscribes :reload, 'template[/tmp/somefile]', :immediately end
where the subscribes notification is used to reload the service using the template specified by the template resource.
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.erbfrom the/templatesdirectory 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_packageis a variable that is used to identify which platforms apply to which install packages - the package resource uses the
cron_packagevariable 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 provider Chef::Provider::Service::Init notifies :restart, 'service[nginx]', :immediately end
where by using the default provider for the service, the recipe is telling the chef-client to determine the specific provider to be used during the chef-client run based on the platform of the node on which the recipe will run.
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.
© Chef Software, Inc.
Licensed under the Creative Commons Attribution 3.0 Unported License.
The Chef™ Mark and Chef Logo are either registered trademarks/service marks or trademarks/servicemarks of Chef, in the United States and other countries and are used with Chef Inc's permission.
We are not affiliated with, endorsed or sponsored by Chef Inc.
https://docs-archive.chef.io/release/11-18/resource_service.html