This page is generated from the Chef Infra Client source code. To suggest a change, edit the service.rb file and submit a pull request to the Chef Infra Client repository.
Use the service resource to manage a service.
The full syntax for all of the properties that are available to the service resource is:
service 'name' do
init_command String
options Array, String
parameters Hash
pattern String
priority Integer, String, Hash
reload_command String, false
restart_command String, false
run_levels Array
service_name String # default value: 'name' unless specified
start_command String, false
status_command String, false
stop_command String, false
supports Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil}
timeout Integer # default value: 900
user String
action Symbol # defaults to :nothing if not specified
endwhere:
service is the resource.name is the name given to the resource block.action identifies which steps Chef Infra Client will take to bring the node into the desired state.init_command, options, parameters, pattern, priority, reload_command, restart_command, run_levels, service_name, start_command, status_command, stop_command, supports, timeout, and user are the properties available to this resource.The service resource has the following actions:
:disableDisabled 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.:enableAutomatic 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:reload:restart:start:stopThe service resource has the following properties:
init_command 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, Chef Infra Client will use the default init command for the service provider being used.
options Solaris platform only. Options to pass to the service command. See the svcadm manual for details of possible options.
parameters Upstart only: A hash of parameters to pass to the service command for use in the service definition.
pattern The value provided to 'service_name' or the resource block's name The pattern to look for in the process table.
priority 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 The command used to tell a service to reload its configuration.
restart_command The command used to restart a service.
run_levels RHEL platforms only: Specific run_levels the service will run under.
service_name The resource block's name An optional property to set the service name if it differs from the resource block’s name.
start_command The command used to start a service.
status_command The command used to check the run status for a service.
stop_command The command used to stop a service.
supports {"restart" => nil, "reload" => nil, "status" => nil} A list of properties that controls how Chef Infra 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, Chef Infra 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, Chef Infra 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 900 The amount of time (in seconds) to wait before timing out.
user systemd only: A username to run the service under.
New in Chef Client 12.21
Chef resources include common properties, notifications, and resource guards.
The following properties are common to every resource:
compile_timeRuby Type: true, false | Default Value: false
Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).
ignore_failureRuby Type: true, false, :quiet | Default Value: false
Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.
retriesRuby Type: Integer | Default Value: 0
The number of attempts to catch exceptions and retry the resource.
retry_delayRuby Type: Integer | Default Value: 2
The delay in seconds between retry attempts.
sensitiveRuby Type: true, false | Default Value: false
Ensure that sensitive resource data is not logged by Chef Infra Client.
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.
If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.
A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:
:beforeSpecifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayedDefault. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra 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
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.
If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.
A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:
:beforeSpecifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayedDefault. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra 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
A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:
0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.
PropertiesThe following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:
not_ifPrevent a resource from executing when the condition returns true.
only_ifAllow a resource to execute only if the condition returns true.
The following examples demonstrate various approaches for using the service resource in recipes:
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
if redhat?
service_name 'redhat_name'
else
service_name 'other_name'
end
supports restart: true
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:
authorized_ip.erb from the /templates directory that is used to set the IP address values based on the variables specified in the recipenode.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 packagescron_package variable to determine how to install the crond application on various nodes (with various platforms)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:
# 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
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
© 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.chef.io/resources/service/