Resources Reference

[edit on GitHub]

A resource is a statement of configuration policy that:

  • Describes the desired state for a configuration item
  • Declares the steps needed to bring that item to the desired state
  • Specifies a resource type—such as package, template, or service
  • Lists additional details (also known as resource properties), as necessary
  • Are grouped into recipes, which describe working configurationst

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::Platform class maps providers to platforms (and platform versions). At the beginning of every chef-client run, Ohai verifies the platform and platform_version attributes on each node. The chef-client then uses those values to identify the correct provider, build an instance of that provider, identify the current state of the resource, do the specified action, and then mark the resource as updated (if changes were made).

For example:

directory '/tmp/folder' do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

The chef-client will look up the provider for the directory resource, which happens to be Chef::Provider::Directory, call load_current_resource to create a directory["/tmp/folder"] resource, and then, based on the current state of the directory, do the specified action, which in this case is to create a directory called /tmp/folder. If the directory already exists, nothing will happen. If the directory was changed in any way, the resource is marked as updated.

This reference describes each of the resources available to the chef-client, including a list of actions, a list of properties, (when applicable) a list of providers, and examples of using each resource.

Common Functionality

The properties and actions in this section apply to all resources.

Actions

The following actions may be used with any resource:

:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.

Examples

The following examples show how to use common actions in a recipe.

Use the :nothing action

service 'memcached' do
  action :nothing
  supports :status => true, :start => true, :stop => true, :restart => true
end

Properties

The following properties are common to every resource:

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

provider

Ruby Type: Chef Class

Optional. The chef-client will attempt to determine the correct provider during the chef-client run, and then choose the best/correct provider based on configuration data collected at the start of the chef-client run. In general, a provider does not need to be specified.

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.

sensitive

Ruby Types: TrueClass, FalseClass

Ensure that sensitive resource data is not logged by the chef-client. Default value: false. This property only applies to the execute, file and template resources.

supports

Ruby Type: Hash

A hash of options that contains hints about the capabilities of a resource. The chef-client may use these hints to help identify the correct provider. This property is only used by a small number of providers, including user and service.

Provider

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

Examples

The following examples show how to use common properties in a recipe.

Use the ignore_failure common property

gem_package 'syntax' do
  action :install
  ignore_failure true
end

Use the provider common property

package 'some_package' do
  provider Chef::Provider::Package::Rubygems
end

Use the supports common property

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

Use the supports and providers common properties

service 'some_service' do
  provider Chef::Provider::Service::Upstart
  supports :status => true, :restart => true, :reload => true
  action [ :enable, :start ]
end

Guards

A guard property can be used to evaluate the state of a node during the execution phase of the chef-client run. Based on the results of this evaluation, a guard property is then used to tell the chef-client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 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.
  • A block is executed as Ruby code that must return either 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 the chef-client to do nothing.

Attributes

The following properties can be used to define a guard that is evaluated during the execution phase of the chef-client run:

not_if
Prevent a resource from executing when the condition returns true.
only_if
Allow a resource to execute only if the condition returns true.

Arguments

The following arguments can be used with the not_if or only_if guard properties:

:user

Specify the user that a command will run as. For example:

not_if 'grep adam /etc/passwd', :user => 'adam'
:group

Specify the group that a command will run as. For example:

not_if 'grep adam /etc/passwd', :group => 'adam'
:environment

Specify a Hash of environment variables to be set. For example:

not_if 'grep adam /etc/passwd', :environment => {
  'HOME' => '/home/adam'
}
:cwd

Set the current working directory before running a command. For example:

not_if 'grep adam passwd', :cwd => '/etc'
:timeout

Set a timeout for a command. For example:

not_if 'sleep 10000', :timeout => 10

not_if Examples

The following examples show how to use not_if as a condition in a recipe:

Create a file, but not if an attribute has a specific value

The following example shows how to use the not_if condition to create a file based on a template and using the presence of an attribute value on the node to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  not_if { node[:some_value] }
end

Create a file with a Ruby block, but not if “/etc/passwd” exists

The following example shows how to use the not_if condition to create a file based on a template and then Ruby code to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  not_if do
    File.exist?('/etc/passwd')
  end
end

Create a file with Ruby block that has curly braces, but not if “/etc/passwd” exists

The following example shows how to use the not_if condition to create a file based on a template and using a Ruby block (with curly braces) to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  not_if { File.exist?('/etc/passwd' )}
end

Create a file using a string, but not if “/etc/passwd” exists

The following example shows how to use the not_if condition to create a file based on a template and using a string to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  not_if 'test -f /etc/passwd'
end

Install a file from a remote location using bash

The following is an example of how to install the foo123 module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following:

  • Declares three variables
  • Gets the Nginx file from a remote location
  • Installs the file using Bash to the path specified by the src_filepath variable
# the following code sample is similar to the ``upload_progress_module``
# recipe in the ``nginx`` cookbook:
# https://github.com/chef-cookbooks/nginx

src_filename = "foo123-nginx-module-v#{
  node['nginx']['foo123']['version']
}.tar.gz"
src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}"
extract_path = "#{
  Chef::Config['file_cache_path']
  }/nginx_foo123_module/#{
  node['nginx']['foo123']['checksum']
}"

remote_file 'src_filepath' do
  source node['nginx']['foo123']['url']
  checksum node['nginx']['foo123']['checksum']
  owner 'root'
  group 'root'
  mode '0755'
end

bash 'extract_module' do
  cwd ::File.dirname(src_filepath)
  code <<-EOH
    mkdir -p #{extract_path}
    tar xzf #{src_filename} -C #{extract_path}
    mv #{extract_path}/*/* #{extract_path}/
    EOH
  not_if { ::File.exist?(extract_path) }
end

only_if Examples

The following examples show how to use only_if as a condition in a recipe:

Create a file, but only if an attribute has a specific value

The following example shows how to use the only_if condition to create a file based on a template and using the presence of an attribute on the node to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  only_if { node[:some_value] }
end

Create a file with a Ruby block, but only if “/etc/passwd” does not exist

The following example shows how to use the only_if condition to create a file based on a template, and then use Ruby to specify a condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  only_if do ! File.exist?('/etc/passwd') end
end

Create a file using a string, but only if “/etc/passwd” exists

The following example shows how to use the only_if condition to create a file based on a template and using a string to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  only_if 'test -f /etc/passwd'
end

Guard Interpreters

Any resource that passes a string command may also specify the interpreter that will be used to evaluate that string command. This is done by using the guard_interpreter property to specify a script-based resource.

Attributes

The guard_interpreter property may be set to any of the following values:

:bash
Evaluates a string command using the bash resource.
:batch
Evaluates a string command using the batch resource. Default value (within a batch resource block): :batch.
:csh
Evaluates a string command using the csh resource.
:default
Default. Executes the default interpreter as identified by the chef-client.
:perl
Evaluates a string command using the perl resource.
:powershell_script
Evaluates a string command using the powershell_script resource. Default value (within a batch resource block): :powershell_script.
:python
Evaluates a string command using the python resource.
:ruby
Evaluates a string command using the ruby resource.

Inheritance

The guard_interpreter property is set to :default by default for the bash, csh, perl, python, and ruby resources. When the guard_interpreter property is set to :default, not_if or only_if guard statements do not inherit properties that are defined by the script-based resource.

Warning

The batch and powershell_script resources inherit properties by default. The guard_interpreter property is set to :batch or :powershell_script automatically when using a not_if or only_if guard statement within a batch or powershell_script resource, respectively.

For example, the not_if guard statement in the following resource example does not inherit the environment property:

bash 'javatooling' do
  environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home'
  code 'java-based-daemon-ctl.sh -start'
  not_if 'java-based-daemon-ctl.sh -test-started'
end

and requires adding the environment property to the not_if guard statement so that it may use the JAVA_HOME path as part of its evaluation:

bash 'javatooling' do
  environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home'
  code 'java-based-daemon-ctl.sh -start'
  not_if 'java-based-daemon-ctl.sh -test-started', :environment => 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home'
end

To inherit properties, add the guard_interpreter property to the resource block and set it to the appropriate value:

  • :bash for bash
  • :csh for csh
  • :perl for perl
  • :python for python
  • :ruby for ruby

For example, using the same example as from above, but this time adding the guard_interpreter property and setting it to :bash:

bash 'javatooling' do
  guard_interpreter :bash
  environment 'JAVA_HOME' => '/usr/lib/java/jdk1.7/home'
  code 'java-based-daemon-ctl.sh -start'
  not_if 'java-based-daemon-ctl.sh -test-started'
end

The not_if statement now inherits the environment property and will use the JAVA_HOME path as part of its evaluation.

Examples

For example, the following code block will ensure the command is evaluated using the default intepreter as identified by the chef-client:

resource 'name' do
  guard_interpreter :default
  # code
end

Lazy Evaluation

In some cases, the value for a property cannot be known until the execution phase of a chef-client run. In this situation, using lazy evaluation of property values can be helpful. Instead of a property being assigned a value, it may instead be assigned a code block. The syntax for using lazy evaluation is as follows:

attribute_name lazy { code_block }

where lazy is used to tell the chef-client to evaluate the contents of the code block later on in the resource evaluation process (instead of immediately) and { code_block } is arbitrary Ruby code that provides the value.

For example, a resource that is not doing lazy evaluation:

template 'template_name' do
  # some attributes
  path '/foo/bar'
end

and a resource block that is doing lazy evaluation:

template 'template_name' do
  # some attributes
  path lazy { ' some Ruby code ' }
end

In the previous examples, the first resource uses the value /foo/bar and the second resource uses the value provided by the code block, as long as the contents of that code block are a valid resource property.

The following example shows how to use lazy evaluation with template variables:

template '/tmp/canvey_island.txt' do
  source 'canvey_island.txt.erb'
  variables(
    lazy {
      { :canvey_island => node.run_state['sea_power'] }
    }
  )
end

Notifications

A notification is a property on a resource that listens to other resources in the resource collection and then takes actions based on the notification type (notifies or subscribes).

Timers

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 very end of the chef-client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

Notifies

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 notifiy more than one resource; use a notifies statement for each resource to be notified.

The syntax for notifies is:

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

The following examples show how to use the notifies notification in a recipe.

Delay notifications

template '/etc/nagios3/configures-nagios.conf' do
  # other parameters
  notifies :run, 'execute[test-nagios-config]', :delayed
end

Notify immediately

By default, notifications are :delayed, that is they are queued up as they are triggered, and then executed at the very end of a chef-client run. To run an action immediately, use :immediately:

template '/etc/nagios3/configures-nagios.conf' do
  # other parameters
  notifies :run, 'execute[test-nagios-config]', :immediately
end

and then the chef-client would immediately run the following:

execute 'test-nagios-config' do
  command 'nagios3 --verify-config'
  action :nothing
end

Notify multiple resources

template '/etc/chef/server.rb' do
  source 'server.rb.erb'
  owner 'root'
  group 'root'
  mode '0755'
  notifies :restart, 'service[chef-solr]', :delayed
  notifies :restart, 'service[chef-solr-indexer]', :delayed
  notifies :restart, 'service[chef-server]', :delayed
end

Notify in a specific order

To notify multiple resources, and then have these resources run in a certain order, do something like the following:

execute 'foo' do
  command '...'
  notifies :create, 'template[baz]', :immediately
  notifies :install, 'package[bar]', :immediately
  notifies :run, 'execute[final]', :immediately
end

template 'baz' do
  ...
  notifies :run, 'execute[restart_baz]', :immediately
end

package 'bar'

execute 'restart_baz'

execute 'final' do
  command '...'
end

where the sequencing will be in the same order as the resources are listed in the recipe: execute 'foo', template 'baz', execute [restart_baz], package 'bar', and execute 'final'.

Reload a service

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  notifies :reload, 'service[apache]', :immediately
end

Restart a service when a template is modified

template '/etc/www/configures-apache.conf' do
  notifies :restart, 'service[apache]', :immediately
end

Send notifications to multiple resources

To send notifications to multiple resources, just use multiple attributes. Multiple attributes will get sent to the notified resources in the order specified.

template '/etc/netatalk/netatalk.conf' do
  notifies :restart, 'service[afpd]', :immediately
  notifies :restart, 'service[cnid]', :immediately
end

service 'afpd'
service 'cnid'

Execute a command using a template

The following example shows how to set up IPv4 packet forwarding using the execute resource to run a command named forward_ipv4 that uses a template defined by the template resource:

execute 'forward_ipv4' do
  command 'echo > /proc/.../ipv4/ip_forward'
  action :nothing
end

template '/etc/file_name.conf' do
  source 'routing/file_name.conf.erb'
  notifies :run, 'execute[forward_ipv4]', :delayed
end

where the command property for the execute resource contains the command that is to be run and the source property for the template resource specifies which template to use. The notifies property for the template specifies that the execute[forward_ipv4] (which is defined by the execute resource) should be queued up and run at the end of the chef-client run.

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.

Notify when a remote source changes

remote_file '/tmp/couch.png' do
  source 'http://couchdb.apache.org/img/sketch.png'
  action :nothing
end

http_request 'HEAD http://couchdb.apache.org/img/sketch.png' do
  message ''
  url 'http://couchdb.apache.org/img/sketch.png'
  action :head
  if File.exist?('/tmp/couch.png')
    headers 'If-Modified-Since' => File.mtime('/tmp/couch.png').httpdate
  end
  notifies :create, 'remote_file[/tmp/couch.png]', :immediately
end

Subscribes

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.

The syntax for subscribes is:

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

The following examples show how to use the subscribes notification in a recipe.

Prevent restart and reconfigure if configuration is broken

Use the :nothing action (common to all resources) to prevent an application from restarting, and then use the subscribes notification to ask the broken configuration to be reconfigured immediately:

execute 'test-nagios-config' do
  command 'nagios3 --verify-config'
  action :nothing
  subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately
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.

Stash a file in a data bag

The following example shows how to use the ruby_block resource to stash a BitTorrent file in a data bag so that it can be distributed to nodes in the organization.

# the following code sample comes from the ``seed`` recipe
# in the following cookbook: https://github.com/mattray/bittorrent-cookbook

ruby_block 'share the torrent file' do
  block do
    f = File.open(node['bittorrent']['torrent'],'rb')
    #read the .torrent file and base64 encode it
    enc = Base64.encode64(f.read)
    data = {
      'id'=>bittorrent_item_id(node['bittorrent']['file']),
      'seed'=>node.ipaddress,
      'torrent'=>enc
    }
    item = Chef::DataBagItem.new
    item.data_bag('bittorrent')
    item.raw_data = data
    item.save
  end
  action :nothing
  subscribes :create, "bittorrent_torrent[#{node['bittorrent']['torrent']}]", :immediately
end

Relative Paths

The following relative paths can be used with any resource:

#{ENV['HOME']}
Use to return the ~ path in Linux and Mac OS X or the %HOMEPATH% in Microsoft Windows.

Examples

template "#{ENV['HOME']}/chef-getting-started.txt" do
  source 'chef-getting-started.txt.erb'
  mode '0755'
end

Run in Compile Phase

The chef-client processes recipes in two phases:

  1. First, each resource in the node object is identified and a resource collection is built. All recipes are loaded in a specific order, and then the actions specified within each of them are identified. This is also referred to as the “compile phase”.
  2. Next, the chef-client configures the system based on the order of the resources in the resource collection. Each resource is mapped to a provider, which then examines the node and performs the necessary steps to complete the action. This is also referred to as the “execution phase”.

Typically, actions are processed during the execution phase of the chef-client run. However, sometimes it is necessary to run an action during the compile phase. For example, a resource can be configured to install a package during the compile phase to ensure that application is available to other resources during the execution phase.

Note

Use the chef_gem resource to install gems that are needed by the chef-client during the execution phase.

run_action

Use .run_action(:some_action) at the end of a resource block to run the specified action during the compile phase. For example:

resource_name 'foo' do
  action :nothing
end.run_action(:some_action)

where action is set to :nothing to ensure the run_action is run during the compile phase and not later during the execution phase.

The following examples show when (and when not) to use run_action.

Update a package cache

Sometimes it is necessary to ensure that an operating system’s package cache is up to date before installing packages. For example, on Debian or Ubuntu systems, the Apt cache should be updated:

if node['apt']['compile_time_update'] && ( !::File.exist?('/var/lib/apt/periodic/update-success-stamp') || !::File.exist?(first_run_file) )
  e = bash 'apt-get-update at compile time' do
    code <<-EOH
      apt-get update
      touch #{first_run_file}
    EOH
    ignore_failure true
    only_if { apt_installed? }
    action :nothing
  end
  e.run_action(:run)
end

where e.run_action(:run) tells the chef-client to run the apt-get update command during the compile phase. This example can be found in the default.rb recipe of the apt cookbook that is maintained by Chef.

Use the chef_gem resource for Ruby gems

A very common use case us to install a gem during the compile phase so that it will be available to the chef-client during the execution phase. This is why the chef_gem resource exists. For example, this:

chef_gem 'foo' do
  action :install
end

is effectively the same as

gem_package 'foo' do
  action :nothing
end.run_action(:install)
Gem.clear_paths

but without needing to define a run_action.

Notifications will not work

Resources that are executed during the compile phase cannot notify other resources. For example:

execute 'ifconfig'

p = package 'vim-enhanced' do
  action :nothing
  notifies :run, 'execute[ifconfig]', :immediately
end
p.run_action(:install)

A better approach in this type of situation is to install the package before the resource collection is built to ensure that it is available to other resources later on.

Atomic File Updates

Atomic updates are used with file-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out.

Atomic updates are enabled by default. They can be managed globally using the file_atomic_update setting in the client.rb file. They can be managed on a per-resource basis using the atomic_update property that is available with the cookbook_file, file, remote_file, and template resources.

Note

On certain platforms, and after a file has been moved into place, the chef-client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, the chef-client will fix up the security contexts after a file has been moved into the correct location by running the restorecon command. On the Microsoft Windows platform, the chef-client will create files so that ACL inheritance works as expected.

Windows File Security

To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes.

Access Control Lists (ACLs)

The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; the chef-client will apply them to the file or directory as required. The syntax for the rights property is as follows:

rights permission, principal, option_type => value

where

permission

Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control.

These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read.

(For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.)

principal
Use to specify a group or user name. This is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. The chef-client does not need to know if a principal is a user or a group.
option_type

A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types:

Option Type Description
:applies_to_children Specify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).
:applies_to_self Indicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.
:one_level_deep Indicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
end

or:

rights :read, ['Administrators','Everyone']
rights :full_control, 'Users', :applies_to_children => true
rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true

Some other important things to know when using the rights attribute:

  • Only inherited rights remain. All existing explicit rights on the object are removed and replaced.
  • If rights are not specified, nothing will be changed. The chef-client does not clear out the rights on a file or directory if rights are not specified.
  • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration.

Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
  deny_rights :read, ['Julian', 'Lewis']
end

or:

deny_rights :full_control, ['Sally']

Inheritance

By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The inherits property can be used to specifically tell the chef-client to apply (or not apply) inherited rights from its parent directory.

For example, the following example specifies the rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
end

and then the following example specifies how to use inheritance to deny access to the child directory:

directory 'C:\mordor\mount_doom' do
  rights :full_control, 'MORDOR\Sauron'
  inherits false # Sauron is the only person who should have any sort of access
end

If the deny_rights permission were to be used instead, something could slip through unless all users and groups were denied.

Another example also shows how to specify rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
  rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there
end

but then not use the inherits property to deny those rights on a child directory:

directory 'C:\mordor\mount_doom' do
  deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough
end

Because the inherits property is not specified, the chef-client will default it to true, which will ensure that security settings for existing files remain unchanged.

Resources

The following resources are built-in to the chef-client:

  • apt_package (based on the package resource)
  • apt_repository
  • apt_update
  • bash
  • batch
  • bff_package (based on the package resource)
  • breakpoint
  • chef_gem (based on the package resource)
  • chef_handler (available from the chef_handler cookbook)
  • chocolatey_package (based on the package resource)
  • cookbook_file
  • cron
  • csh
  • deploy (including git and Subversion)
  • directory
  • dpkg_package (based on the package resource)
  • dsc_resource
  • dsc_script
  • easy_install_package (based on the package resource)
  • env
  • erl_call
  • execute
  • file
  • freebsd_package (based on the package resource)
  • gem_package (based on the package resource)
  • git
  • group
  • homebrew_package (based on the package resource)
  • http_request
  • ifconfig
  • ips_package (based on the package resource)
  • ksh
  • link
  • log
  • macports_package (based on the package resource)
  • mdadm
  • mount
  • ohai
  • openbsd_package (based on the package resource)
  • osx_profile
  • package
  • pacman_package (based on the package resource)
  • paludis_package (based on the package resource)
  • perl
  • portage_package (based on the package resource)
  • powershell_script
  • python
  • reboot
  • registry_key
  • remote_directory
  • remote_file
  • route
  • rpm_package (based on the package resource)
  • ruby
  • ruby_block
  • script
  • service
  • smartos_package (based on the package resource)
  • solaris_package (based on the package resource)
  • subversion
  • template
  • user
  • windows_package
  • windows_service
  • yum (based on the package resource)
  • yum_repository

See below for more information about each of these resources, their related actions and properties, and examples of how these resources can be used in recipes.

apt_package

[edit on GitHub]

Use the apt_package resource to manage packages for the Debian and Ubuntu platforms.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, the chef-client will use details that are collected by Ohai at the start of the chef-client run to determine the correct package application. Using the package resource allows a recipe to be authored in a way that allows it to be used across many platforms.

Syntax

A apt_package resource block manages a package on a node, typically by installing it. The simplest use of the apt_package resource is:

apt_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

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

apt_package 'name' do
  default_release            String
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  provider                   Chef::Provider::Package::Apt
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where

  • apt_package tells the chef-client to manage a package
  • 'name' is the name of the package
  • action identifies which steps the chef-client will take to bring the node into the desired state
  • default_release, options, package_name, provider, source, timeout, and version 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

This resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:lock

Locks the apt package to a specific version.

New in Chef client 12.16.

:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:reconfig
Reconfigure a package. This action requires a response file.
:remove
Remove a package.
:unlock

Unlocks the apt package so that it can be upgraded to a newer version.

New in Chef client 12.16.

:upgrade
Install a package and/or ensure that a package is the latest version.

Properties

This resource has the following properties:

default_release

Ruby Type: String

The default release. For example: stable.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

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 notifiy 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 very 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: String

One (or more) additional options that are passed to the command. For example, common apt-get directives, such as --no-install-recommends. See the apt-get man page for the full list.

package_name

Ruby Types: String, Array

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

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

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.

source

Ruby Type: String

Optional. The direct path to a dpkg or deb package.

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.

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 very 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
timeout

Ruby Types: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Types: String, Array

The version of a package to be installed or upgraded.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Yum, Apt, Zypper, or Chocolatey package managers. Specifing multiple packages and/or versions allows a single transaction to:

  • Download the specified packages and versions via a single HTTP transaction
  • Update or install multiple packages with a single resource during the chef-client run

For example, installing multiple packages:

package ['package1', 'package2']

Upgrading multiple packages:

package ['package1', 'package2']  do
  action :upgrade
end

Removing multiple packages:

package ['package1', 'package2']  do
  action :remove
end

Purging multiple packages:

package ['package1', 'package2']  do
  action :purge
end

Notifications, via an implicit name:

package ['package1', 'package2']  do
  action :nothing
end

log 'call a notification' do
  notifies :install, 'package[package1, package2]', :immediately
end

Note

Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the package_name or version properties.

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Package, package
When this short name is used, the chef-client will attempt to determine the correct provider during the chef-client run.
Chef::Provider::Package::Apt, apt_package
The provider for the Debian and Ubuntu platforms.

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.

Install a package using package manager

apt_package 'name of package' do
  action :install
end

Install a package using local file

apt_package 'jwhois' do
  action :install
  source '/path/to/jwhois.deb'
end

Install without using recommend packages as a dependency

package 'apache2' do
  options '--no-install-recommends'
end

apt_repository

[edit on GitHub]

Use the apt_repository resource to additional APT repositories. Adding a new repository will update apt package cache immediately.

New in Chef Client 12.9.

Syntax

An apt_repository resource specifies APT repository information and adds an additional APT repository to the existing list of repositories:

apt_repository 'zenoss' do
  uri        'http://dev.zenoss.org/deb'
  components ['main', 'stable']
end

where

  • apt_repository is the resource
  • name is the name of the resource block
  • uri is a base URI for the distribution where the apt packages are located at
  • components is an array of package groupings in the repository

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

apt_repository 'name' do
   repo_name             String
   uri                   String
   distribution          String
   components            Array
   arch                  String
   trusted               TrueClass, FalseClass
   deb_src               TrueClass, FalseClass
   keyserver             String
   key                   String
   key_proxy             String
   cookbook              String
   cache_rebuild         TrueClass, FalseClass
   sensitive             TrueClass, FalseClass
end

where

  • apt_repository is the resource
  • name is the name of the resource block
  • repo_name, uri, distribution, components, arch, trusted, deb_src, keyserver, key, key_proxy, cookbook, cache_rebuild, and sensitive 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

This resource has the following actions:

:add
Default. Creates a repository file at /etc/apt/sources.list.d/ and builds the repository listing.
:remove
Removes the repository listing.

Properties

This resource has the following properties:

repo_name

Ruby Type: String

The name of the channel to discover.

uri

Ruby Type: String

The base of the Debian distribution.

distribution

Ruby Type: String

Usually a codename, such as something like karmic, lucid or maverick.

components

Ruby Type: Array

Package groupings, such as ‘main’ and ‘stable’. Default value: empty array.

arch

Ruby Type: String

Constrain packages to a particular CPU architecture such as 'i386' or 'amd64'. Default value: nil.

trusted

Ruby Type: TrueClass, FalseClass

Determines whether you should treat all packages from this repository as authenticated regardless of signature. Default value: false.

deb_src

Ruby Type: TrueClass, FalseClass

Determines whether or not to add the repository as a source repo as well. Default value: false.

keyserver

Ruby Type: String

The GPG keyserver where the key for the repo should be retrieved. Default value: “keyserver.ubuntu.com”.

key

Ruby Type: String

If a keyserver is provided, this is assumed to be the fingerprint; otherwise it can be either the URI to the GPG key for the repo, or a cookbook_file. Default value: nil.

key_proxy

Ruby Type: String

If set, a specified proxy is passed to GPG via http-proxy=. Default value: nil.

cookbook

Ruby Type: String

If key should be a cookbook_file, specify a cookbook where the key is located for files/default. Default value is nil, so it will use the cookbook where the resource is used.

cache_rebuild

Ruby Type: TrueClass, FalseClass

Determines whether to rebuild the apt package cache. Default value: true.

sensitive

Ruby Type: TrueClass, FalseClass

Determines whether sensitive resource data (such as key information) is not logged by the chef-client. Default value: false.

Providers

This resource has the following provider:

Chef::Provider::AptRepository, apt_repository
The default provider for all platforms.

Examples

Add repository with basic settings

apt_repository 'zenoss' do
  uri        'http://dev.zenoss.org/deb'
  components ['main', 'stable']
end

Enable Ubuntu multiverse repositories

apt_repository 'security-ubuntu-multiverse' do
  uri          'http://security.ubuntu.com/ubuntu'
  distribution 'trusty-security'
  components   ['multiverse']
  deb_src      true
end

Add the Nginx PPA, autodetect the key and repository url

apt_repository 'nginx-php' do
  uri          'ppa:nginx/stable'
  distribution node['lsb']['codename']
end

Add the JuJu PPA, grab the key from the keyserver, and add source repo

apt_repository 'juju' do
  uri 'http://ppa.launchpad.net/juju/stable/ubuntu'
  components ['main']
  distribution 'trusty'
  key 'C8068B11'
  keyserver 'keyserver.ubuntu.com'
  action :add
  deb_src true
end

Add the Cloudera Repo of CDH4 packages for Ubuntu 12.04 on AMD64

apt_repository 'cloudera' do
  uri          'http://archive.cloudera.com/cdh4/ubuntu/precise/amd64/cdh'
  arch         'amd64'
  distribution 'precise-cdh4'
  components   ['contrib']
  key          'http://archive.cloudera.com/debian/archive.key'
end

Remove a repository from the list

apt_repository 'zenoss' do
  action :remove
end

apt_update

[edit on GitHub]

Use the apt_update resource to manage Apt repository updates on Debian and Ubuntu platforms.

New in Chef Client 12.7.

Syntax

A apt_update resource block defines the update frequency for Apt repositories:

apt_update 'name' do
  frequency                  Integer
  action                     Symbol # defaults to :periodic if not specified
end

where

  • apt_update is the resource
  • name is the name of the resource block
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • frequency is a property 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:

:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:periodic
Update the Apt repository at the interval specified by the frequency property.
:update
Update the Apt repository at the start of the chef-client run.

Properties

This resource has the following properties:

frequency

Ruby Type: Integer

The frequency at which Apt repository updates are made. Use this property when the :periodic action is specified. Default value: 86400.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

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 notifiy 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 very 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
provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

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.

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.

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 very 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

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.

Update the Apt repository at a specified interval

apt_update 'all platforms' do
  frequency 86400
  action :periodic
end

Update the Apt repository at the start of a chef-client run

apt_update if node['platform_family'] == 'debian' do
  action :update
end

bash

[edit on GitHub]

Use the bash resource to execute scripts using the Bash interpreter. This resource may also use any of the actions and properties that are available to the execute resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Note

The bash script resource (which is based on the script resource) is different from the ruby_block resource because Ruby code that is run with this resource is created as a temporary file and executed like other script resources, rather than run inline.

Syntax

A bash resource block executes scripts using Bash:

bash 'extract_module' do
  cwd ::File.dirname(src_filepath)
  code <<-EOH
    mkdir -p #{extract_path}
    tar xzf #{src_filename} -C #{extract_path}
    mv #{extract_path}/*/* #{extract_path}/
    EOH
  not_if { ::File.exist?(extract_path) }
end

where

  • cwd specifies the directory from which the command is run
  • code specifies the command to run

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

bash 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  notifies                   # see description
  path                       Array
  provider                   Chef::Provider::Script::Bash
  returns                    Integer, Array
  subscribes                 # see description
  timeout                    Integer, Float
  user                       String, Integer
  umask                      String, Integer
  action                     Symbol # defaults to :run if not specified
end

where

  • bash is the resource
  • name is the name of the resource block
  • cwd is the location from which the command is run
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • code, creates, cwd, environment, flags, group, path, provider, returns, timeout, user, and umask 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

This resource has the following actions:

:nothing
Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it.
:run
Default. Run a script.

Properties

This resource has the following properties:

code

Ruby Type: String

A quoted (” ”) string of code to be executed.

creates

Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd

Ruby Type: String

The current working directory.

environment

Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags

Ruby Type: String

One or more command line flags that are passed to the interpreter when a command is invoked.

group

Ruby Types: String, Integer

The group name or group ID that must be changed before running a command.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

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 notifiy 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 very 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
path

Ruby Type: Array

An array of paths to use when searching for a command. These paths are not added to the command’s environment $PATH. The default value uses the system path.

Warning

For example:

bash 'mycommand' do
  environment 'PATH' => "/my/path/to/bin:#{ENV['PATH']}"
end
provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

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.

returns

Ruby Types: Integer, Array

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. Default value: 0.

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.

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 very 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
timeout

Ruby Types: Integer, Float

The amount of time (in seconds) a command is to wait before timing out. Default value: 3600.

user

Ruby Types: String, Integer

The user name or user ID that should be changed before running a command.

umask

Ruby Types: String, Integer

The file mode creation mask, or umask.

Guards

A guard property can be used to evaluate the state of a node during the execution phase of the chef-client run. Based on the results of this evaluation, a guard property is then used to tell the chef-client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 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.
  • A block is executed as Ruby code that must return either 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 the chef-client to do nothing.

Attributes

The following properties can be used to define a guard that is evaluated during the execution phase of the chef-client run:

not_if
Prevent a resource from executing when the condition returns true.
only_if
Allow a resource to execute only if the condition returns true.

Arguments

The following arguments can be used with the not_if or only_if guard properties:

:user

Specify the user that a command will run as. For example:

not_if 'grep adam /etc/passwd', :user => 'adam'
:group

Specify the group that a command will run as. For example:

not_if 'grep adam /etc/passwd', :group => 'adam'
:environment

Specify a Hash of environment variables to be set. For example:

not_if 'grep adam /etc/passwd', :environment => {
  'HOME' => '/home/adam'
}
:cwd

Set the current working directory before running a command. For example:

not_if 'grep adam passwd', :cwd => '/etc'
:timeout

Set a timeout for a command. For example:

not_if 'sleep 10000', :timeout => 10

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Script, script
When this short name is used, the chef-client will determine the correct provider during the chef-client run.
Chef::Provider::Script::Bash, bash
The provider for the Bash command interpreter.

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.

Use a named provider to run a script

bash 'install_something' do
  user 'root'
  cwd '/tmp'
  code <<-EOH
  wget http://www.example.com/tarball.tar.gz
  tar -zxf tarball.tar.gz
  cd tarball
  ./configure
  make
  make install
  EOH
end

Install a file from a remote location using bash

The following is an example of how to install the foo123 module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following:

  • Declares three variables
  • Gets the Nginx file from a remote location
  • Installs the file using Bash to the path specified by the src_filepath variable
# the following code sample is similar to the ``upload_progress_module``
# recipe in the ``nginx`` cookbook:
# https://github.com/chef-cookbooks/nginx

src_filename = "foo123-nginx-module-v#{
  node['nginx']['foo123']['version']
}.tar.gz"
src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}"
extract_path = "#{
  Chef::Config['file_cache_path']
  }/nginx_foo123_module/#{
  node['nginx']['foo123']['checksum']
}"

remote_file 'src_filepath' do
  source node['nginx']['foo123']['url']
  checksum node['nginx']['foo123']['checksum']
  owner 'root'
  group 'root'
  mode '0755'
end

bash 'extract_module' do
  cwd ::File.dirname(src_filepath)
  code <<-EOH
    mkdir -p #{extract_path}
    tar xzf #{src_filename} -C #{extract_path}
    mv #{extract_path}/*/* #{extract_path}/
    EOH
  not_if { ::File.exist?(extract_path) }
end

Install an application from git using bash

The following example shows how Bash can be used to install a plug-in for rbenv named ruby-build, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which ruby-build is located, and then runs a command.

 git "#{Chef::Config[:file_cache_path]}/ruby-build" do
   repository 'git://github.com/sstephenson/ruby-build.git'
   reference 'master'
   action :sync
 end

 bash 'install_ruby_build' do
   cwd '#{Chef::Config[:file_cache_path]}/ruby-build'
   user 'rbenv'
   group 'rbenv'
   code <<-EOH
     ./install.sh
     EOH
   environment 'PREFIX' => '/usr/local'
end

To read more about ruby-build, see here: https://github.com/sstephenson/ruby-build.

Store certain settings

The following recipe shows how an attributes file can be used to store certain settings. An attributes file is located in the attributes/ directory in the same cookbook as the recipe which calls the attributes file. In this example, the attributes file specifies certain settings for Python that are then used across all nodes against which this recipe will run.

Python packages have versions, installation directories, URLs, and checksum files. An attributes file that exists to support this type of recipe would include settings like the following:

default['python']['version'] = '2.7.1'

if python['install_method'] == 'package'
  default['python']['prefix_dir'] = '/usr'
else
  default['python']['prefix_dir'] = '/usr/local'
end

default['python']['url'] = 'http://www.python.org/ftp/python'
default['python']['checksum'] = '80e387...85fd61'

and then the methods in the recipe may refer to these values. A recipe that is used to install Python will need to do the following:

  • Identify each package to be installed (implied in this example, not shown)
  • Define variables for the package version and the install_path
  • Get the package from a remote location, but only if the package does not already exist on the target system
  • Use the bash resource to install the package on the node, but only when the package is not already installed
#  the following code sample comes from the ``oc-nginx`` cookbook on |github|: https://github.com/cookbooks/oc-nginx

version = node['python']['version']
install_path = "#{node['python']['prefix_dir']}/lib/python#{version.split(/(^\d+\.\d+)/)[1]}"

remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do
  source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2"
  checksum node['python']['checksum']
  mode '0755'
  not_if { ::File.exist?(install_path) }
end

bash 'build-and-install-python' do
  cwd Chef::Config[:file_cache_path]
  code <<-EOF
    tar -jxvf Python-#{version}.tar.bz2
    (cd Python-#{version} && ./configure #{configure_options})
    (cd Python-#{version} && make && make install)
  EOF
  not_if { ::File.exist?(install_path) }
end

batch

[edit on GitHub]

Use the batch resource to execute a batch script using the cmd.exe interpreter. The batch resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. This resource inherits actions (:run and :nothing) and properties (creates, cwd, environment, group, path, timeout, and user) from the execute resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Syntax

A batch resource block executes a batch script using the cmd.exe interpreter:

batch 'echo some env vars' do
  code <<-EOH
    echo %TEMP%
    echo %SYSTEMDRIVE%
    echo %PATH%
    echo %WINDIR%
    EOH
end

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

batch 'name' do
  architecture               Symbol
  code                       String
  command                    String, Array
  creates                    String
  cwd                        String
  flags                      String
  group                      String, Integer
  guard_interpreter          Symbol
  interpreter                String
  notifies                   # see description
  provider                   Chef::Provider::Batch
  returns                    Integer, Array
  subscribes                 # see description
  timeout                    Integer, Float
  user                       String
  password                   String
  domain                     String
  action                     Symbol # defaults to :run if not specified
end

where

  • batch is the resource
  • name is the name of the resource block
  • command is the command to be run and cwd is the location from which the command is run
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • architecture, code, command, creates, cwd, flags, group, guard_interpreter, interpreter, provider, returns, timeout, user`, password` and domain` 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

This resource has the following actions:

:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:run
Run a batch file.

Properties

This resource has the following properties:

architecture

Ruby Type: Symbol

The architecture of the process under which a script is executed. If a value is not provided, the chef-client defaults to the correct value for the architecture, as determined by Ohai. An exception is raised when anything other than :i386 is specified for a 32-bit process. Possible values: :i386 (for 32-bit processes) and :x86_64 (for 64-bit processes).

code

Ruby Type: String

A quoted (” ”) string of code to be executed.

command

Ruby Types: String, Array

The name of the command to be executed.

creates

Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd

Ruby Type: String

The current working directory from which a command is run.

flags

Ruby Type: String

One or more command line flags that are passed to the interpreter when a command is invoked.

group

Ruby Types: String, Integer

The group name or group ID that must be changed before running a command.

guard_interpreter

Ruby Type: Symbol

Default value: :batch. When this property is set to :batch, the 64-bit version of the cmd.exe shell will be used to evaluate strings values for the not_if and only_if properties. Set this value to :default to use the 32-bit version of the cmd.exe shell.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

interpreter

Ruby Type: String

The script interpreter to use during code execution. Changing the default value of this property is not supported.

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 notifiy 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 very 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
provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

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.

returns

Ruby Types: Integer, Array

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. Default value: 0.

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.

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 very 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
timeout

Ruby Types: Integer, Float

The amount of time (in seconds) a command is to wait before timing out. Default value: 3600.

user

Ruby Types: String

The user name of the user identity with which to launch the new process. Default value: nil. The user name may optionally be specifed with a domain, i.e. domainuser or user@my.dns.domain.com via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified.

password

Ruby Types: String

Windows only: The password of the user specified by the user property. Default value: nil. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified.

domain

Ruby Types: String

Windows only: The domain of the user user specified by the user property. Default value: nil. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property.

Note

See http://technet.microsoft.com/en-us/library/bb490880.aspx for more information about the cmd.exe interpreter.

Guards

A guard property can be used to evaluate the state of a node during the execution phase of the chef-client run. Based on the results of this evaluation, a guard property is then used to tell the chef-client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 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.
  • A block is executed as Ruby code that must return either 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 the chef-client to do nothing.

Attributes

The following properties can be used to define a guard that is evaluated during the execution phase of the chef-client run:

not_if
Prevent a resource from executing when the condition returns true.
only_if
Allow a resource to execute only if the condition returns true.

Arguments

The following arguments can be used with the not_if or only_if guard properties:

:user

Specify the user that a command will run as. For example:

not_if 'grep adam /etc/passwd', :user => 'adam'
:group

Specify the group that a command will run as. For example:

not_if 'grep adam /etc/passwd', :group => 'adam'
:environment

Specify a Hash of environment variables to be set. For example:

not_if 'grep adam /etc/passwd', :environment => {
  'HOME' => '/home/adam'
}
:cwd

Set the current working directory before running a command. For example:

not_if 'grep adam passwd', :cwd => '/etc'
:timeout

Set a timeout for a command. For example:

not_if 'sleep 10000', :timeout => 10

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.

Unzip a file, and then move it

To run a batch file that unzips and then moves Ruby, do something like:

batch 'unzip_and_move_ruby' do
  code <<-EOH
    7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z
      -oC:\\source -r -y
    xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y
    EOH
end

batch 'echo some env vars' do
  code <<-EOH
    echo %TEMP%
    echo %SYSTEMDRIVE%
    echo %PATH%
    echo %WINDIR%
    EOH
end

or:

batch 'unzip_and_move_ruby' do
  code <<-EOH
    7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z
      -oC:\\source -r -y
    xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y
    EOH
end

batch 'echo some env vars' do
  code 'echo %TEMP%\\necho %SYSTEMDRIVE%\\necho %PATH%\\necho %WINDIR%'
end

Run a command as an alternate user

Note: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator.

This right can be added and checked in a recipe using this example:

# Add 'SeAssignPrimaryTokenPrivilege' for the user
Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege')

# Check if the user has 'SeAssignPrimaryTokenPrivilege' rights
Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege')

The following example shows how to run mkdir test_dir from a chef-client run as an alternate user.

# Passing only username and password
batch 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username"
 password "password"
end

# Passing username and domain
batch 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 domain "domain"
 user "username"
 password "password"
end

# Passing username = 'domain-name\\username'. No domain is passed
batch 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "domain-name\\username"
 password "password"
end

# Passing username = 'username@domain-name'. No domain is passed
batch 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username@domain-name"
 password "password"
end

bff_package

[edit on GitHub]

Use the bff_package resource to manage packages for the AIX platform using the installp utility. When a package is installed from a local file, it must be added to the node using the remote_file or cookbook_file resources.

Note

A Backup File Format (BFF) package may not have a .bff file extension. The chef-client will still identify the correct provider to use based on the platform, regardless of the file extension.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, the chef-client will use details that are collected by Ohai at the start of the chef-client run to determine the correct package application. Using the package resource allows a recipe to be authored in a way that allows it to be used across many platforms.

Syntax

A bff_package resource block manages a package on a node, typically by installing it. The simplest use of the bff_package resource is:

bff_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

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

bff_package 'name' do
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  provider                   Chef::Provider::Package::Aix
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where

  • bff_package tells the chef-client to manage a package
  • 'name' is the name of the package
  • action identifies which steps the chef-client will take to bring the node into the desired state
  • options, package_name, provider, source, timeout, and version 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

This resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:remove
Remove a package.

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.

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 notifiy 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 very 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: String

One (or more) additional options that are passed to the command.

package_name

Ruby Types: String, Array

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

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

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.

source

Ruby Type: String

Required. The path to a package in the local file system. The AIX platform requires source to be a local file system path because installp does not retrieve packages using HTTP or FTP.

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.

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 very 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
timeout

Ruby Types: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Types: String, Array

The version of a package to be installed or upgraded.

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Package, package
When this short name is used, the chef-client will attempt to determine the correct provider during the chef-client run.
Chef::Provider::Package::Aix, bff_package
The provider for the AIX platform. Can be used with the options attribute.

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.

Install a package

The bff_package resource is the default package provider on the AIX platform. The base package resource may be used, and then when the platform is AIX, the chef-client will identify the correct package provider. The following examples show how to install part of the IBM XL C/C++ compiler.

Using the base package resource:

package 'xlccmp.13.1.0' do
  source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0'
  action :install
end

Using the bff_package resource:

bff_package 'xlccmp.13.1.0' do
  source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0'
  action :install
end

breakpoint

[edit on GitHub]

Use the breakpoint resource to add breakpoints to recipes. Run the chef-shell in chef-client mode, and then use those breakpoints to debug recipes. Breakpoints are ignored by the chef-client during an actual chef-client run. That said, breakpoints are typically used to debug recipes only when running them in a non-production environment, after which they are removed from those recipes before the parent cookbook is uploaded to the Chef server.

New in Chef Client 12.0.

Syntax

A breakpoint resource block creates a breakpoint in a recipe:

breakpoint 'name' do
  action :break
end

where

  • :break will tell the chef-client to stop running a recipe; can only be used when the chef-client is being run in chef-shell mode

Actions

This resource has the following actions:

:break
Use to add a breakpoint to a recipe.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.

Properties

This resource does not have any properties.

Debug Recipes with chef-shell

chef-shell is a recipe debugging tool that allows the use of breakpoints within recipes. chef-shell runs as an Interactive Ruby (IRb) session. chef-shell supports both recipe and attribute file syntax, as well as interactive debugging features.

Modes

chef-shell is tool that is run using an Interactive Ruby (IRb) session. chef-shell currently supports recipe and attribute file syntax, as well as interactive debugging features. chef-shell has three run modes:

Mode Description
Standalone Default. No cookbooks are loaded, and the run-list is empty.
Solo chef-shell acts as a chef-solo client. It attempts to load the chef-solo configuration file and JSON attributes. If the JSON attributes set a run-list, it will be honored. Cookbooks will be loaded in the same way that chef-solo loads them. chef-solo mode is activated with the -s or --solo command line option, and JSON attributes are specified in the same way as for chef-solo, with -j /path/to/chef-solo.json.
Client chef-shell acts as a chef-client. During startup, it reads the chef-client configuration file and contacts the Chef server to get attributes and cookbooks. The run-list will be set in the same way as normal chef-client runs. chef-client mode is activated with the -z or --client options. You can also specify the configuration file with -c CONFIG and the server URL with -S SERVER_URL.

Configure

chef-shell determines which configuration file to load based on the following:

  1. If a configuration file is specified using the -c option, chef-shell will use the specified configuration file
  2. When chef-shell is started using a named configuration as an argument, chef-shell will search for a chef-shell.rb file in that directory under ~/.chef. For example, if chef-shell is started using production as the named configuration, the chef-shell will load a configuration file from ~/.chef/production/chef_shell.rb
  3. If a named configuration is not provided, chef-shell will attempt to load the chef-shell.rb file from the .chef directory. For example: ~/.chef/chef_shell.rb
  4. If a chef-shell.rb file is not found, chef-shell will attempt to load the client.rb file
  5. If a chef-shell.rb file is not found, chef-shell will attempt to load the solo.rb file
chef-shell.rb

The chef-shell.rb file can be used to configure chef-shell in the same way as the client.rb file is used to configure the chef-client. For example, to configure chef-shell to authenticate to the Chef server, copy the node_name, client_key, and chef_server_url settings from the knife.rb file:

node_name                'your-knife-clientname'
client_key               File.expand_path('~/.chef/my-client.pem')
chef_server_url          'https://api.opscode.com/organizations/myorg'

and then add them to the chef-shell.rb file. Other configuration possibilities include disabling Ohai plugins (which will speed up the chef-shell boot process) or including arbitrary Ruby code in the chef-shell.rb file.

Run as a chef-client

By default, chef-shell loads in standalone mode and does not connect to the Chef server. The chef-shell can be run as a chef-client to verify functionality that is only available when the chef-client connects to the Chef server, such as search functionality or accessing data stored in data bags.

chef-shell can use the same credentials as knife when connecting to a Chef server. Make sure that the settings in chef-shell.rb are the same as those in knife.rb, and then use the -z option as part of the command. For example:

$ chef-shell -z

Manage

When chef-shell is configured to access a Chef server, chef-shell can list, show, search for and edit cookbooks, clients, nodes, roles, environments, and data bags.

The syntax for managing objects on the Chef server is as follows:

$ chef (named_configuration) > items.command

where:

  • named_configuration is a named configuration, such as production, staging, or test
  • items is the type of item to search for: cookbooks, clients, nodes, roles, environments or a data bag
  • command is the command: list, show, find, or edit

For example, to list all of the nodes in a configuration named “preprod”:

$ chef (preprod) > nodes.list

to return something similar to:

$ => [node[i-f09a939b], node[i-049a936f], node[i-eaaaa581], node[i-9154b1fb],
     node[i-6a213101], node[i-c2687aa9], node[i-7abeaa11], node[i-4eb8ac25],
     node[i-9a2030f1], node[i-a06875cb], node[i-145f457f], node[i-e032398b],
     node[i-dc8c98b7], node[i-6afdf401], node[i-f49b119c], node[i-5abfab31],
     node[i-78b8ac13], node[i-d99678b3], node[i-02322269], node[i-feb4a695],
     node[i-9e2232f5], node[i-6e213105], node[i-cdde3ba7], node[i-e8bfb083],
     node[i-743c2c1f], node[i-2eaca345], node[i-aa7f74c1], node[i-72fdf419],
     node[i-140e1e7f], node[i-f9d43193], node[i-bd2dc8d7], node[i-8e7f70e5],
     node[i-78f2e213], node[i-962232fd], node[i-4c322227], node[i-922232f9],
     node[i-c02728ab], node[i-f06c7b9b]]

The list command can take a code block, which will applied (but not saved) to each object that is returned from the server. For example:

$ chef (preprod) > nodes.list {|n| puts "#{n.name}: #{n.run_list}" }

to return something similar to:

$ => i-f09a939b: role[lb], role[preprod], recipe[aws]
     i-049a936f: role[lb], role[preprod], recipe[aws]
     i-9154b1fb: recipe[erlang], role[base], role[couchdb], role[preprod],
     i-6a213101: role[chef], role[preprod]
     # more...

The show command can be used to display a specific node. For example:

$ chef (preprod) > load_balancer = nodes.show('i-f09a939b')

to return something similar to:

$ => node[i-f09a939b]

or:

$ chef (preprod) > load_balancer.ec2.public_hostname

to return something similar to:

$ => "ec2-111-22-333-44.compute-1.amazonaws.com"

The find command can be used to search the Chef server from the chef-shell. For example:

$ chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*')

A code block can be used to format the results. For example:

$ chef (preprod) > pp nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id } and nil

to return something similar to:

$ => ["ami-f8927a91",
      "ami-f8927a91",
      "ami-a89870c1",
      "ami-a89870c1",
      "ami-a89870c1",
      "ami-a89870c1",
      "ami-a89870c1"
      # and more...

Or:

chef (preprod) > amis = nodes.find(:ec2_public_hostname => 'ec2*') {|n| n.ec2.ami_id }
chef (preprod) > puts amis.uniq.sort

to return something similar to:

$ => ami-4b4ba522
     ami-a89870c1
     ami-eef61587
     ami-f8927a91

Use Breakpoints

chef-shell allows the current position in a run-list to be manipulated during a chef-client run. Add breakpoints to a recipe to take advantage of this functionality.

Step Through Run-list

To explore how using the breakpoint to manually step through a chef-client run, create a simple recipe in chef-shell:

$ chef > recipe_mode
  chef:recipe > echo off
  chef:recipe > file "/tmp/before-breakpoint"
  chef:recipe > breakpoint "foo"
  chef:recipe > file "/tmp/after-breakpoint"

and then run the chef-client:

$ chef:recipe > run_chef
  [Fri, 15 Jan 2010 14:17:49 -0800] DEBUG: Processing file[/tmp/before-breakpoint]
  [Fri, 15 Jan 2010 14:17:49 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File
  [Fri, 15 Jan 2010 14:17:49 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint
  [Fri, 15 Jan 2010 14:17:49 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new']
  [Fri, 15 Jan 2010 14:17:49 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint

The chef-client ran the first resource before the breakpoint (file[/tmp/before-breakpoint]), but then stopped after execution. The chef-client attempted to name the breakpoint after its position in the source file, but the chef-client was confused because the resource was entered interactively. From here, chef-shell can resume the chef-client run:

$ chef:recipe > chef_run.resume
  [Fri, 15 Jan 2010 14:27:08 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint

A quick view of the /tmp directory shows that the following files were created:

after-breakpoint
before-breakpoint

The chef-client run can also be rewound, and then stepped through.

$ chef:recipe > Chef::Log.level = :debug # debug logging won't turn on automatically in this case
    => :debug
  chef:recipe > chef_run.rewind
    => 0
  chef:recipe > chef_run.step
  [Fri, 15 Jan 2010 14:40:52 -0800] DEBUG: Processing file[/tmp/before-breakpoint]
  [Fri, 15 Jan 2010 14:40:52 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File
    => 1
  chef:recipe > chef_run.step
  [Fri, 15 Jan 2010 14:40:54 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new']
  [Fri, 15 Jan 2010 14:40:54 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint
    => 2
  chef:recipe > chef_run.step
  [Fri, 15 Jan 2010 14:40:56 -0800] DEBUG: Processing file[/tmp/after-breakpoint]
  [Fri, 15 Jan 2010 14:40:56 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File
    => 3

From the output, the rewound run-list is shown, but when the resources are executed again, they will repeat their checks for the existence of files. If they exist, the chef-client will skip creating them. If the files are deleted, then:

$ chef:recipe > ls("/tmp").grep(/breakpoint/).each {|f| rm "/tmp/#{f}" }
    => ["after-breakpoint", "before-breakpoint"]

Rewind, and then resume the chef-client run to get the expected results:

$ chef:recipe > chef_run.rewind
  chef:recipe > chef_run.resume
  [Fri, 15 Jan 2010 14:48:56 -0800] DEBUG: Processing file[/tmp/before-breakpoint]
  [Fri, 15 Jan 2010 14:48:56 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File
  [Fri, 15 Jan 2010 14:48:56 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint
  [Fri, 15 Jan 2010 14:48:56 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new']
  [Fri, 15 Jan 2010 14:48:56 -0800] DEBUG: [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new'] using Chef::Provider::Breakpoint
  chef:recipe > chef_run.resume
  [Fri, 15 Jan 2010 14:49:20 -0800] DEBUG: Processing file[/tmp/after-breakpoint]
  [Fri, 15 Jan 2010 14:49:20 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File
  [Fri, 15 Jan 2010 14:49:20 -0800] INFO: Creating file[/tmp/after-breakpoint] at /tmp/after-breakpoint
Debug Existing Recipe

chef-shell can be used to debug existing recipes. The recipe first needs to be added to a run-list for the node, so that it is cached when starting chef-shell and then used for debugging. chef-shell will report which recipes are being cached when it is started:

loading configuration: none (standalone session)
Session type: standalone
Loading..............done.

This is the chef-shell.
 Chef Version: 12.17.44
 https://www.chef.io/
 /

run `help' for help, `exit' or ^D to quit.

Ohai2u YOURNAME@!
chef (12.17.44)>

To just load one recipe from the run-list, go into the recipe and use the include_recipe command. For example:

$ chef > recipe_mode
  chef:recipe > include_recipe "getting-started"
    => [#<Chef::Recipe:0x10256f9e8 @cookbook_name="getting-started",
  ... output truncated ...

To load all of the recipes from a run-list, use code similar to the following:

node.run_list.expand(node.chef_environment).recipes.each do |r|
  include_recipe r
end

After the recipes that are to be debugged have been loaded, use the run_chef command to run them.

Advanced Debugging

In chef-shell, it is possible to get extremely verbose debugging using the tracing feature in Interactive Ruby (IRb). chef-shell provides a shortcut for turning tracing on and off. For example:

$ chef > tracing on
  /Users/danielsdeleo/.rvm/ree-1.8.7-2009.10/lib/ruby/1.8/tracer.rb:150: warning: tried to create Proc object without a block
  /Users/danielsdeleo/.rvm/ree-1.8.7-2009.10/lib/ruby/1.8/tracer.rb:146: warning: tried to create Proc object without a block
  tracing is on
    => nil

and:

$ chef > tracing off
  #0:(irb):3:Object:-: tracing off
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:108:Shell::Extensions::ObjectCoreExtensions:>:       def off
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:109:Shell::Extensions::ObjectCoreExtensions:-:         :off
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:110:Shell::Extensions::ObjectCoreExtensions:<:       end
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:273:main:>:       def tracing(on_or_off)
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:274:main:-:         conf.use_tracer = on_or_off.on_off_to_bool
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:161:Shell::Extensions::Symbol:>:       def on_off_to_bool
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:162:Shell::Extensions::Symbol:-:         self.to_s.on_off_to_bool
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:148:Shell::Extensions::String:>:       def on_off_to_bool
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:149:Shell::Extensions::String:-:         case self
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:153:Shell::Extensions::String:-:           false
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:157:Shell::Extensions::String:<:       end
  #0:/opt/chef/embedded/lib/ruby/gems/1.9.3/gems/chef-11.4.4/lib/chef/shell/ext.rb:163:Shell::Extensions::Symbol:<:       end
  tracing is off
   => nil
  chef >

Debug Examples

The following examples show how to use chef-shell.

“Hello World”

This example shows how to run chef-shell in standalone mode. (For chef-solo or chef-client modes, you would need to run chef-shell using the -s or -z command line options, and then take into consideration the necessary configuration settings.)

When the chef-client is installed using RubyGems or a package manager, chef-shell should already be installed. When the chef-client is run from a git clone, it will be located in chef/bin/chef shell. To start chef-shell, just run it without any options. You’ll see the loading message, then the banner, and then the chef-shell prompt:

$ bin/chef-shell
  loading configuration: none (standalone session)
  Session type: standalone
  Loading..............done.

  This is the chef-shell.
   Chef Version: 12.17.44
   https://www.chef.io/
   /

  run `help' for help, `exit' or ^D to quit.

  Ohai2u YOURNAME@!
  chef (12.17.44)>

(Use the help command to print a list of supported commands.) Use the recipe_mode command to switch to recipe context:

$ chef > recipe_mode
  chef:recipe_mode >

Typing is evaluated in the same context as recipes. Create a file resource:

$ chef:recipe_mode > file "/tmp/ohai2u_shef"
    => #<Chef::Resource::File:0x1b691ac
       @enclosing_provider=nil,
       @resource_name=:file,
       @before=nil,
       @supports={},
       @backup=5,
       @allowed_actions=[:nothing, :create, :delete, :touch, :create_if_missing],
       @only_if=nil,
       @noop=nil,
       @collection=#<Chef::ResourceCollection:0x1b9926c
       @insert_after_idx=nil,
       @resources_by_name={"file[/tmp/ohai2u_shef]"=>0},
       @resources=[#<Chef::Resource::File:0x1b691ac ...>]>,
       @updated=false,
       @provider=nil,
       @node=<Chef::Node:0xdeeaae
       @name="eigenstate.local">,
       @recipe_name=nil,
       @not_if=nil,
       @name="/tmp/ohai2u_shef",
       @action="create",
       @path="/tmp/ohai2u_shef",
       @source_line="/Users/danielsdeleo/ruby/chef/chef/(irb#1) line 1",
       @params={},
       @actions={},
       @cookbook_name=nil,
       @ignore_failure=false>

(The previous example was formatted for presentation.) At this point, chef-shell has created the resource and put it in the run-list, but not yet created the file. To initiate the chef-client run, use the run_chef command:

$ chef:recipe_mode > run_chef
  [Fri, 15 Jan 2010 10:42:47 -0800] DEBUG: Processing file[/tmp/ohai2u_shef]
  [Fri, 15 Jan 2010 10:42:47 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File
  [Fri, 15 Jan 2010 10:42:47 -0800] INFO: Creating file[/tmp/ohai2u_shef] at /tmp/ohai2u_shef
    => true

chef-shell can also switch to the same context as attribute files. Set an attribute with the following syntax:

$ chef:recipe_mode > attributes_mode
  chef:attributes > set[:hello] = "ohai2u-again"
    => "ohai2u-again"
  chef:attributes >

Switch back to recipe_mode context and use the attributes:

$ chef:attributes > recipe_mode
    => :attributes
  chef:recipe_mode > file "/tmp/#{node.hello}"

Now, run the chef-client again:

$ chef:recipe_mode > run_chef
  [Fri, 15 Jan 2010 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u_shef]
  [Fri, 15 Jan 2010 10:53:22 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File
  [Fri, 15 Jan 2010 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u-again]
  [Fri, 15 Jan 2010 10:53:22 -0800] DEBUG: file[/tmp/ohai2u-again] using Chef::Provider::File
  [Fri, 15 Jan 2010 10:53:22 -0800] INFO: Creating file[/tmp/ohai2u-again] at /tmp/ohai2u-again
    => true
  chef:recipe_mode >

Because the first resource (file[/tmp/ohai2u_shef]) is still in the run-list, it gets executed again. And because that file already exists, the chef-client doesn’t attempt to re-create it. Finally, the files were created using the ls method:

$ chef:recipe_mode > ls("/tmp").grep(/ohai/)
    => ["ohai2u-again", "ohai2u_shef"]
      Shell Tutorial
Get Specific Nodes

To get a list of nodes using a recipe named postfix use search(:node,"recipe:postfix"). To get a list of nodes using a sub-recipe named delivery, use chef-shell. For example:

search(:node, 'recipes:postfix\:\:delivery')

Note

Single (‘ ‘) vs. double (” ”) is important. This is because a backslash () needs to be included in the string, instead of having Ruby interpret it as an escape.

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.

A recipe without a breakpoint

yum_key node['yum']['elrepo']['key'] do
  url  node['yum']['elrepo']['key_url']
  action :add
end

yum_repository 'elrepo' do
  description 'ELRepo.org Community Enterprise Linux Extras Repository'
  key node['yum']['elrepo']['key']
  mirrorlist node['yum']['elrepo']['url']
  includepkgs node['yum']['elrepo']['includepkgs']
  exclude node['yum']['elrepo']['exclude']
  action :create
end

The same recipe with breakpoints

breakpoint "before yum_key node['yum']['repo_name']['key']" do
  action :break
end

yum_key node['yum']['repo_name']['key'] do
  url  node['yum']['repo_name']['key_url']
  action :add
end

breakpoint "after yum_key node['yum']['repo_name']['key']" do
  action :break
end

breakpoint "before yum_repository 'repo_name'" do
  action :break
end

yum_repository 'repo_name' do
  description 'description'
  key node['yum']['repo_name']['key']
  mirrorlist node['yum']['repo_name']['url']
  includepkgs node['yum']['repo_name']['includepkgs']
  exclude node['yum']['repo_name']['exclude']
  action :create
end

breakpoint "after yum_repository 'repo_name'" do
  action :break
end

where the name of each breakpoint is an arbitrary string. In the previous examples, the names are used to indicate if the breakpoint is before or after a resource, and then also to specify which resource.

chef_gem

[edit on GitHub]

Warning

The chef_gem and gem_package resources are both used to install Ruby gems. For any machine on which the chef-client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to the chef-client. Use the chef_gem resource to install gems into the instance of Ruby that is dedicated to the chef-client. Use the gem_package resource to install all other gems (i.e. install gems system-wide).

Use the chef_gem resource to install a gem only for the instance of Ruby that is dedicated to the chef-client. When a gem is installed from a local file, it must be added to the node using the remote_file or cookbook_file resources.

The chef_gem resource works with all of the same properties and options as the gem_package resource, but does not accept the gem_binary property because it always uses the CurrentGemEnvironment under which the chef-client is running. In addition to performing actions similar to the gem_package resource, the chef_gem resource does the following:

  • Runs its actions immediately, before convergence, allowing a gem to be used in a recipe immediately after it is installed
  • Runs Gem.clear_paths after the action, ensuring that gem is aware of changes so that it can be required immediately after it is installed

Syntax

A chef_gem resource block manages a package on a node, typically by installing it. The simplest use of the chef_gem resource is:

chef_gem 'package_name'

which will install the named gem using all of the default options and the default action (:install).

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

chef_gem 'name' do
  clear_sources              TrueClass, FalseClass
  compile_time               TrueClass, FalseClass
  notifies                   # see description
  options                    String
  package_name               String # defaults to 'name' if not specified
  provider                   Chef::Provider::Package::Rubygems
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String
  action                     Symbol # defaults to :install if not specified
end

where

  • chef_gem tells the chef-client to manage a gem
  • 'name' is the name of the gem
  • action identifies which steps the chef-client will take to bring the node into the desired state
  • clear_sources, compile_time, options, package_name, provider, source, timeout, and version 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

This resource has the following actions:

:install
Default. Install a gem. If a version is specified, install the specified version of the gem.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:purge
Purge a gem. This action typically removes the configuration files as well as the gem.
:reconfig
Reconfigure a gem. This action requires a response file.
:remove
Remove a gem.
:upgrade
Install a gem and/or ensure that a gem is the latest version.

Properties

This resource has the following properties:

clear_sources

Ruby Types: TrueClass, FalseClass

Set to true to download a gem from the path specified by the source property (and not from RubyGems). Default value: false.

Note

Another approach is to use the gem_package resource, and then specify the gem_binary location to the RubyGems directory that is used by Chef. For example:

gem_package 'gem_name' do
  gem_binary Chef::Util::PathHelper.join(Chef::Config.embedded_dir,'bin','gem')
  action :install
end
compile_time

Ruby Types: TrueClass, FalseClass

Controls the phase during which a gem is installed on a node. Set to true to install a gem while the resource collection is being built (the “compile phase”). Set to false to install a gem while the chef-client is configuring the node (the “converge phase”). Possible values: nil (for verbose warnings), true (to warn once per chef-client run), or false (to remove all warnings). Recommended value: false.

To suppress warnings for cookbooks authored prior to chef-client 12.1, use a respond_to? check to ensure backward compatibility. For example:

chef_gem 'aws-sdk' do
  compile_time false if respond_to?(:compile_time)
end

Warning

If you are using chef-sugar—a community cookbook—it must be version 3.0.1 (or higher) to use the previous example. If you are using an older version of chef-sugar, the following workaround is required:

chef_gem 'gem_name' do
  compile_time true if Chef::Resource::ChefGem.instance_methods(false).include?(:compile_time)
end

See this blog post for more background on this behavior.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

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 notifiy 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 very 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: String

One (or more) additional options that are passed to the command.

package_name

Ruby Types: String

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

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

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.

source

Ruby Type: String

Optional. The path to a gem in the local file system.

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.

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 very 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
timeout

Ruby Types: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Types: String

The version of a gem to be installed or upgraded.

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Package, package
When this short name is used, the chef-client will attempt to determine the correct provider during the chef-client run.
Chef::Provider::Package::Rubygems, chef_gem
Can be used with the options attribute.

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.

Compile time vs. converge time installation of gems

To install a gem while the chef-client is configuring the node (the “converge phase”), set the compile_time property to false:

chef_gem 'right_aws' do
  compile_time false
  action :install
end

To install a gem while the resource collection is being built (the “compile phase”), set the compile_time property to true:

chef_gem 'right_aws' do
  compile_time true
  action :install
end

Install MySQL for Chef

execute 'apt-get update' do
  ignore_failure true
  action :nothing
end.run_action(:run) if node['platform_family'] == 'debian'

node.set['build_essential']['compiletime'] = true
include_recipe 'build-essential'
include_recipe 'mysql::client'

node['mysql']['client']['packages'].each do |mysql_pack|
  resources("package[#{mysql_pack}]").run_action(:install)
end

chef_gem 'mysql'

chef_handler

[edit on GitHub]

Use the chef_handler resource to enable handlers during a chef-client run. The resource allows arguments to be passed to the chef-client, which then applies the conditions defined by the custom handler to the node attribute data collected during the chef-client run, and then processes the handler based on that data.

The chef_handler resource is typically defined early in a node’s run-list (often being the first item). This ensures that all of the handlers will be available for the entire chef-client run.

The chef_handler resource is included with the chef_handler cookbook. This cookbook defines the the resource itself and also provides the location in which the chef-client looks for custom handlers. All custom handlers should be added to the files/default/handlers directory in the chef_handler cookbook.

Handler Types

There are three types of handlers:

Handler Description
exception An exception handler is used to identify situations that have caused a chef-client run to fail. An exception handler can be loaded at the start of a chef-client run by adding a recipe that contains the chef_handler resource to a node’s run-list. An exception handler runs when the failed? property for the run_status object returns true.
report A report handler is used when a chef-client run succeeds and reports back on certain details about that chef-client run. A report handler can be loaded at the start of a chef-client run by adding a recipe that contains the chef_handler resource to a node’s run-list. A report handler runs when the success? property for the run_status object returns true.
start A start handler is used to run events at the beginning of the chef-client run. A start handler can be loaded at the start of a chef-client run by adding the start handler to the start_handlers setting in the client.rb file or by installing the gem that contains the start handler by using the chef_gem resource in a recipe in the chef-client cookbook. (A start handler may not be loaded using the chef_handler resource.)

Exception / Report

Exception and report handlers are used to trigger certain behaviors in response to specific situations, typically identified during a chef-client run.

  • An exception handler is used to trigger behaviors when a defined aspect of a chef-client run fails.
  • A report handler is used to trigger behaviors when a defined aspect of a chef-client run is successful.

Both types of handlers can be used to gather data about a chef-client run and can provide rich levels of data about all types of usage, which can be used later for trending and analysis across the entire organization.

Exception and report handlers are made available to the chef-client run in one of the following ways:

  • By adding the chef_handler resource to a recipe, and then adding that recipe to the run-list for a node. (The chef_handler resource is available from the chef_handler cookbook.)
  • By adding the handler to one of the following settings in the node’s client.rb file: exception_handlers and/or report_handlers

The chef_handler resource allows exception and report handlers to be enabled from within recipes, which can then added to the run-list for any node on which the exception or report handler should run. The chef_handler resource is available from the chef_handler cookbook.

To use the chef_handler resource in a recipe, add code similar to the following:

chef_handler 'name_of_handler' do
  source '/path/to/handler/handler_name'
  action :enable
end

For example, a handler for Growl needs to be enabled at the beginning of the chef-client run:

chef_gem 'chef-handler-growl'

and then is activated in a recipe by using the chef_handler resource:

chef_handler 'Chef::Handler::Growl' do
  source 'chef/handler/growl'
  action :enable
end

Start

A start handler is not loaded into the chef-client run from a recipe, but is instead listed in the client.rb file using the start_handlers attribute. The start handler must be installed on the node and be available to the chef-client prior to the start of the chef-client run. Use the chef-client cookbook to install the start handler.

Start handlers are made available to the chef-client run in one of the following ways:

  • By adding a start handler to the chef-client cookbook, which installs the handler on the node so that it is available to the chef-client at the start of the chef-client run
  • By adding the handler to one of the following settings in the node’s client.rb file: start_handlers

The chef-client cookbook can be configured to automatically install and configure gems that are required by a start handler. For example:

node.set['chef_client']['load_gems']['chef-reporting'] = {
  :require_name => 'chef_reporting',
  :action => :install
}

node.set['chef_client']['config']['start_handlers'] = [
  {
    :class => 'Chef::Reporting::StartHandler',
    :arguments => []
  }
]

include_recipe 'chef-client::config'

Syntax

A chef_handler resource block enables handlers during a chef-client run. Two handlers—JsonFile and ErrorReport—are built into Chef:

chef_handler 'Chef::Handler::JsonFile' do
  source 'chef/handler/json_file'
  arguments :path => '/var/chef/reports'
  action :enable
end

and:

chef_handler 'Chef::Handler::ErrorReport' do
  source 'chef/handler/error_report'
  action :enable
end

show how to enable those handlers in a recipe.

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

chef_handler 'name' do
  arguments                  Array
  class_name                 String
  notifies                   # see description
  source                     String
  subscribes                 # see description
  supports                   Hash
  action                     Symbol
end

where

  • chef_handler is the resource
  • name is the name of the resource block
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • arguments, class_name, source, and supports 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

This resource has the following actions:

:disable
Disable the handler for the current chef-client run on the current node.
:enable
Enable the handler for the current chef-client run on the current node.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.

Properties

This resource has the following properties:

arguments

Ruby Type: Array

An array of arguments that are passed to the initializer for the handler class. Default value: []. For example:

arguments :key1 => 'val1'

or:

arguments [:key1 => 'val1', :key2 => 'val2']
class_name

Ruby Type: String

The name of the handler class. This can be module name-spaced.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

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 notifiy 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 very 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
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.

source

Ruby Type: String

The full path to the handler file or the path to a gem (if the handler ships as part of a Ruby gem).

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.

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 very 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

The type of handler. Possible values: :exception, :report, or :start. Default value: { :report => true, :exception => true }.

Custom Handlers

A custom handler can be created to support any situation. The easiest way to build a custom handler:

  1. Download the chef_handler cookbook
  2. Create a custom handler
  3. Write a recipe using the chef_handler resource
  4. Add that recipe to a node’s run-list, often as the first recipe in that run-list

Syntax

The syntax for a handler can vary, depending on what the the situations the handler is being asked to track, the type of handler being used, and so on. All custom exception and report handlers are defined using Ruby and must be a subclass of the Chef::Handler class.

require 'chef/log'

module ModuleName
  class HandlerName < Chef::Handler
    def report
      # Ruby code goes here
    end
  end
end

where:

  • require ensures that the logging functionality of the chef-client is available to the handler
  • ModuleName is the name of the module as it exists within the Chef library
  • HandlerName is the name of the handler as it is used in a recipe
  • report is an interface that is used to define the custom handler

For example, the following shows a custom handler that sends an email that contains the exception data when a chef-client run fails:

require 'net/smtp'

module OrgName
  class SendEmail < Chef::Handler
    def report
      if run_status.failed? then
        message  = "From: sender_name <sender@example.com>\n"
        message << "To: recipient_address <recipient@example.com>\n"
        message << "Subject: chef-client Run Failed\n"
        message << "Date: #{Time.now.rfc2822}\n\n"
        message << "Chef run failed on #{node.name}\n"
        message << "#{run_status.formatted_exception}\n"
        message << Array(backtrace).join('\n')
        Net::SMTP.start('your.smtp.server', 25) do |smtp|
          smtp.send_message message, 'sender@example', 'recipient@example'
        end
      end
    end
  end
end

and then is used in a recipe like:

send_email 'blah' do
  # recipe code
end

report Interface

The report interface is used to define how a handler will behave and is a required part of any custom handler. The syntax for the report interface is as follows:

def report
  # Ruby code
end

The Ruby code used to define a custom handler will vary significantly from handler to handler. The chef-client includes two default handlers: error_report and json_file. Their use of the report interface is shown below.

The error_report handler:

require 'chef/handler'
require 'chef/resource/directory'

class Chef
  class Handler
    class ErrorReport < ::Chef::Handler
      def report
        Chef::FileCache.store('failed-run-data.json', Chef::JSONCompat.to_json_pretty(data), 0640)
        Chef::Log.fatal("Saving node information to #{Chef::FileCache.load('failed-run-data.json', false)}")
      end
    end
 end
end

The json_file handler:

require 'chef/handler'
require 'chef/resource/directory'

class Chef
  class Handler
    class JsonFile < ::Chef::Handler
      attr_reader :config
      def initialize(config={})
        @config = config
        @config[:path] ||= '/var/chef/reports'
        @config
      end
      def report
        if exception
          Chef::Log.error('Creating JSON exception report')
        else
          Chef::Log.info('Creating JSON run report')
        end
        build_report_dir
        savetime = Time.now.strftime('%Y%m%d%H%M%S')
        File.open(File.join(config[:path], 'chef-run-report-#{savetime}.json'), 'w') do |file|
          run_data = data
          run_data[:start_time] = run_data[:start_time].to_s
          run_data[:end_time] = run_data[:end_time].to_s
          file.puts Chef::JSONCompat.to_json_pretty(run_data)
        end
      end
      def build_report_dir
        unless File.exist?(config[:path])
          FileUtils.mkdir_p(config[:path])
          File.chmod(00700, config[:path])
        end
      end
    end
  end
end

Optional Interfaces

The following interfaces may be used in a handler in the same way as the report interface to override the default handler behavior in the chef-client. That said, the following interfaces are not typically used in a handler and, for the most part, are completely unnecessary for a handler to work properly and/or as desired.

data

The data method is used to return the Hash representation of the run_status object. For example:

def data
  @run_status.to_hash
end
run_report_safely

The run_report_safely method is used to run the report handler, rescuing and logging errors that may arise as the handler runs and ensuring that all handlers get a chance to run during the chef-client run (even if some handlers fail during that run). In general, this method should never be used as an interface in a custom handler unless this default behavior simply must be overridden.

def run_report_safely(run_status)
  run_report_unsafe(run_status)
rescue Exception => e
  Chef::Log.error('Report handler #{self.class.name} raised #{e.inspect}')
  Array(e.backtrace).each { |line| Chef::Log.error(line) }
ensure
  @run_status = nil
end
run_report_unsafe

The run_report_unsafe method is used to run the report handler without any error handling. This method should never be used directly in any handler, except during testing of that handler. For example:

def run_report_unsafe(run_status)
  @run_status = run_status
  report
end

run_status Object

The run_status object is initialized by the chef-client before the report interface is run for any handler. The run_status object keeps track of the status of the chef-client run and will contain some (or all) of the following properties:

Property Description
all_resources A list of all resources that are included in the resource_collection property for the current chef-client run.
backtrace A backtrace associated with the uncaught exception data that caused a chef-client run to fail, if present; nil for a successful chef-client run.
elapsed_time The amount of time between the start (start_time) and end (end_time) of a chef-client run.
end_time The time at which a chef-client run ended.
exception The uncaught exception data which caused a chef-client run to fail; nil for a successful chef-client run.
failed? Show that a chef-client run has failed when uncaught exceptions were raised during a chef-client run. An exception handler runs when the failed? indicator is true.
node The node on which the chef-client run occurred.
run_context An instance of the Chef::RunContext object; used by the chef-client to track the context of the run; provides access to the cookbook_collection, resource_collection, and definitions properties.
start_time The time at which a chef-client run started.
success? Show that a chef-client run succeeded when uncaught exceptions were not raised during a chef-client run. A report handler runs when the success? indicator is true.
updated_resources A list of resources that were marked as updated as a result of the chef-client run.

Note

These properties are not always available. For example, a start handler runs at the beginning of the chef-client run, which means that properties like end_time and elapsed_time are still unknown and will be unavailable to the run_status object.

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.

Enable the CloudkickHandler handler

The following example shows how to enable the CloudkickHandler handler, which adds it to the default handler path and passes the oauth key/secret to the handler’s initializer:

chef_handler "CloudkickHandler" do
  source "#{node['chef_handler']['handler_path']}/cloudkick_handler.rb"
  arguments [node['cloudkick']['oauth_key'], node['cloudkick']['oauth_secret']]
  action :enable
end

Enable handlers during the compile phase

chef_handler "Chef::Handler::JsonFile" do
  source "chef/handler/json_file"
  arguments :path => '/var/chef/reports'
  action :nothing
end.run_action(:enable)

Handle only exceptions

chef_handler "Chef::Handler::JsonFile" do
  source "chef/handler/json_file"
  arguments :path => '/var/chef/reports'
  supports :exception => true
  action :enable
end

Cookbook Versions (a custom handler)

Community member juliandunn created a custom report handler that logs all of the cookbooks and cookbook versions that were used during the chef-client run, and then reports after the run is complete. This handler requires the chef_handler resource (which is available from the chef_handler cookbook).

cookbook_versions.rb:

The following custom handler defines how cookbooks and cookbook versions that are used during the chef-client run will be compiled into a report using the Chef::Log class in the chef-client:

require 'chef/log'

module Opscode
  class CookbookVersionsHandler < Chef::Handler

    def report
      cookbooks = run_context.cookbook_collection
      Chef::Log.info('Cookbooks and versions run: #{cookbooks.keys.map {|x| cookbooks[x].name.to_s + ' ' + cookbooks[x].version} }')
    end
  end
end

default.rb:

The following recipe is added to the run-list for every node on which a list of cookbooks and versions will be generated as report output after every chef-client run.

include_recipe 'chef_handler'

cookbook_file "#{node['chef_handler']['handler_path']}/cookbook_versions.rb" do
  source 'cookbook_versions.rb'
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

chef_handler 'Opscode::CookbookVersionsHandler' do
  source "#{node['chef_handler']['handler_path']}/cookbook_versions.rb"
  supports :report => true
  action :enable
end

This recipe will generate report output similar to the following:

[2013-11-26T03:11:06+00:00] INFO: Chef Run complete in 0.300029878 seconds
[2013-11-26T03:11:06+00:00] INFO: Running report handlers
[2013-11-26T03:11:06+00:00] INFO: Cookbooks and versions run: ["chef_handler 1.1.4", "cookbook_versions_handler 1.0.0"]
[2013-11-26T03:11:06+00:00] INFO: Report handlers complete

JsonFile Handler

The json_file handler is available from the chef_handler cookbook and can be used with exceptions and reports. It serializes run status data to a JSON file. This handler may be enabled in one of the following ways.

By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how the chef-client is being run:

require 'chef/handler/json_file'
report_handlers << Chef::Handler::JsonFile.new(:path => '/var/chef/reports')
exception_handlers << Chef::Handler::JsonFile.new(:path => '/var/chef/reports')

By using the chef_handler resource in a recipe, similar to the following:

chef_handler 'Chef::Handler::JsonFile' do
  source 'chef/handler/json_file'
  arguments :path => '/var/chef/reports'
  action :enable
end

After it has run, the run status data can be loaded and inspected via Interactive Ruby (IRb):

irb(main):001:0> require 'rubygems' => true
irb(main):002:0> require 'json' => true
irb(main):003:0> require 'chef' => true
irb(main):004:0> r = JSON.parse(IO.read('/var/chef/reports/chef-run-report-20110322060731.json')) => ... output truncated
irb(main):005:0> r.keys => ['end_time', 'node', 'updated_resources', 'exception', 'all_resources', 'success', 'elapsed_time', 'start_time', 'backtrace']
irb(main):006:0> r['elapsed_time'] => 0.00246

Register the JsonFile handler

chef_handler "Chef::Handler::JsonFile" do
  source "chef/handler/json_file"
  arguments :path => '/var/chef/reports'
  action :enable
end

ErrorReport Handler

The error_report handler is built into the chef-client and can be used for both exceptions and reports. It serializes error report data to a JSON file. This handler may be enabled in one of the following ways.

By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how the chef-client is being run:

require 'chef/handler/error_report'
report_handlers << Chef::Handler::ErrorReport.new()
exception_handlers << Chef::Handler::ErrorReport.new()

By using the chef_handler resource in a recipe, similar to the following:

chef_handler 'Chef::Handler::ErrorReport' do
  source 'chef/handler/error_report'
  action :enable
end

chocolatey_package

[edit on GitHub]

Use the chocolatey_package resource to manage packages using Chocolatey for the Microsoft Windows platform.

New in Chef Client 12.7.

Warning

The chocolatey_package resource must be specified as chocolatey_package and cannot be shortened to package in a recipe.

Syntax

A chocolatey_package resource block manages packages using Chocolatey for the Microsoft Windows platform. The simplest use of the chocolatey_package resource is:

chocolatey_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

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

chocolatey_package 'name' do
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  provider                   Chef::Provider::Package::Chocolatey
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  returns                    Integer, Array of Integers
  action                     Symbol # defaults to :install if not specified
end

where

  • chocolatey_package tells the chef-client to manage a package
  • 'name' is the name of the package
  • returns specifies the exit code(s) returned by chocolatey package that indicate success. Default is 0.
  • action identifies which steps the chef-client will take to bring the node into the desired state
  • options, package_name, provider, source, timeout, and version 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

This resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:reconfig
Reconfigure a package. This action requires a response file.
:remove
Remove a package.
:uninstall
Uninstall a package.
:upgrade
Install a package and/or ensure that a package is the latest version.

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.

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 notifiy 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 very 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: String

One (or more) additional options that are passed to the command.

package_name

Ruby Types: String, Array

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

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

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.

source

Ruby Type: String

Optional. The path to a package in the local file system.

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.

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 very 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
timeout

Ruby Types: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Types: String, Array

The version of a package to be installed or upgraded.

returns

Ruby Types: Integer, Array of Integers

New in Chef client 12.18.

The exit code(s) returned a chocolatey package that indicate success. Default is 0.

The syntax for returns is:

returns [0, 1605, 1614, 1641]

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Package, package
When this short name is used, the chef-client will attempt to determine the correct provider during the chef-client run.
Chef::Provider::Package::Chocolatey, chocolatey_package
The provider for the Chocolatey package manager for the Microsoft Windows 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.

Install a package

chocolatey_package 'name of package' do
  action :install
end

cookbook_file

[edit on GitHub]

Use the cookbook_file resource to transfer files from a sub-directory of COOKBOOK_NAME/files/ to a specified path located on a host that is running the chef-client. The file is selected according to file specificity, which allows different source files to be used based on the hostname, host platform (operating system, distro, or as appropriate), or platform version. Files that are located in the COOKBOOK_NAME/files/default sub-directory may be used on any platform.

During a chef-client run, the checksum for each local file is calculated and then compared against the checksum for the same file as it currently exists in the cookbook on the Chef server. A file is not transferred when the checksums match. Only files that require an update are transferred from the Chef server to a node.

Syntax

A cookbook_file resource block manages files by using files that exist within a cookbook’s /files directory. For example, to write the home page for an Apache website:

cookbook_file '/var/www/customers/public_html/index.php' do
  source 'index.php'
  owner 'web_admin'
  group 'web_admin'
  mode '0755'
  action :create
end

where

  • '/var/www/customers/public_html/index.php' is path to the file to be created
  • 'index.php' is a file in the /files directory in a cookbook that is used to create that file (the contents of the file in the cookbook will become the contents of the file on the node)
  • owner, group, and mode define the permissions

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

cookbook_file 'name' do
  atomic_update              TrueClass, FalseClass
  backup                     FalseClass, Integer
  cookbook                   String
  force_unlink               TrueClass, FalseClass
  group                      String, Integer
  inherits                   TrueClass, FalseClass
  manage_symlink_source      TrueClass, FalseClass, NilClass
  mode                       String, Integer
  notifies                   # see description
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  provider                   Chef::Provider::CookbookFile
  rights                     Hash
  source                     String, Array
  subscribes                 # see description
  verify                     String, Block
  action                     Symbol # defaults to :create if not specified
end

where

  • cookbook_file is the resource
  • name is the name of the resource block
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • atomic_update, backup, cookbook, force_unlink, group, inherits, manage_symlink_source, mode, owner, path, provider, rights, source, and verify 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

This resource has the following actions:

:create
Default. Create a file. If a file already exists (but does not match), update that file to match.
:create_if_missing
Create a file only if the file does not exist. When the file exists, nothing happens.
:delete
Delete a file.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:touch
Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the file resource.)

Properties

This resource has the following properties:

atomic_update

Ruby Types: TrueClass, FalseClass

Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides file_atomic_update, which is a global setting found in the client.rb file. Default value: true.

backup

Ruby Types: FalseClass, Integer

The number of backups to be kept in /var/chef/backup (for UNIX- and Linux-based platforms) or C:/chef/backup (for the Microsoft Windows platform). Set to false to prevent backups from being kept. Default value: 5.

cookbook

Ruby Type: String

The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook.

force_unlink

Ruby Types: TrueClass, FalseClass

How the chef-client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to true for the chef-client delete the non-file target and replace it with the specified file. Set to false for the chef-client to raise an error. Default value: false.

group

Ruby Types: Integer, String

A string or ID that identifies the group owner by group name, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

inherits

Ruby Types: TrueClass, FalseClass

Microsoft Windows only. Whether a file inherits rights from its parent directory. Default value: true.

manage_symlink_source

Ruby Types: TrueClass, FalseClass, NilClass

Cause the chef-client to detect and manage the source file for a symlink. Possible values: nil, true, or false. When this value is set to nil, the chef-client will manage a symlink’s source file and emit a warning. When this value is set to true, the chef-client will manage a symlink’s source file and not emit a warning. Default value: nil. The default value will be changed to false in a future version.

mode

Ruby Types: Integer, String

If mode is not specified and if the file already exists, the existing mode on the file is used. If mode is not specified, the file does not exist, and the :create action is specified, the chef-client assumes a mask value of '0777' and then applies the umask for the system on which the file is to be created to the mask value. For example, if the umask on a system is '022', the chef-client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

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 notifiy 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 very 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
owner

Ruby Types: Integer, String

A string or ID that identifies the group owner by user name, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path

Ruby Type: String

The path to the destination at which a file is to be created. Default value: the name of the resource block For example: file.txt.

Microsoft Windows: A path that begins with a forward slash (/) will point to the root of the current working directory of the chef-client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended.

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

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.

rights

Ruby Types: Integer, String

Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options.

source

Ruby Types: String, Array

The name of the file in COOKBOOK_NAME/files/default or the path to a file located in COOKBOOK_NAME/files. The path must include the file name and its extension. Can be used to distribute specific files to specific platforms. See “File Specificity” below for more information. See “Syntax” section above for more information.

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.

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 very 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
verify

Ruby Types: String, Block

A block or a string that returns true or false. A string, when true is executed as a system command.

A block is arbitrary Ruby defined within the resource block by using the verify property. When a block is true, the chef-client will continue to update the file as appropriate.

For example, this should return true:

cookbook_file '/tmp/baz' do
  verify { 1 == 1 }
end

This should return true:

cookbook_file '/etc/nginx.conf' do
  verify 'nginx -t -c %{path}'
end

Warning

For releases of the chef-client prior to 12.5 (chef-client 12.4 and earlier) the correct syntax is:

cookbook_file '/etc/nginx.conf' do
  verify 'nginx -t -c %{file}'
end

See GitHub issues https://github.com/chef/chef/issues/3232 and https://github.com/chef/chef/pull/3693 for more information about these differences.

This should return true:

cookbook_file '/tmp/bar' do
  verify { 1 == 1}
end

And this should return true:

cookbook_file '/tmp/foo' do
  verify do |path|
    true
  end
end

Whereas, this should return false:

cookbook_file '/tmp/turtle' do
  verify '/usr/bin/false'
end

If a string or a block return false, the chef-client run will stop and an error is returned.

Note

Use the owner and right properties and avoid the group and mode properties whenever possible. The group and mode properties are not true Microsoft Windows concepts and are provided more for backward compatibility than for best practice.

Warning

For a machine on which SELinux is enabled, the chef-client will create files that correctly match the default policy settings only when the cookbook that defines the action also conforms to the same policy.

Atomic File Updates

Atomic updates are used with file-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out.

Atomic updates are enabled by default. They can be managed globally using the file_atomic_update setting in the client.rb file. They can be managed on a per-resource basis using the atomic_update property that is available with the cookbook_file, file, remote_file, and template resources.

Note

On certain platforms, and after a file has been moved into place, the chef-client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, the chef-client will fix up the security contexts after a file has been moved into the correct location by running the restorecon command. On the Microsoft Windows platform, the chef-client will create files so that ACL inheritance works as expected.

Windows File Security

To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes.

Access Control Lists (ACLs)

The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; the chef-client will apply them to the file or directory as required. The syntax for the rights property is as follows:

rights permission, principal, option_type => value

where

permission

Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control.

These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read.

(For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.)

principal
Use to specify a group or user name. This is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. The chef-client does not need to know if a principal is a user or a group.
option_type

A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types:

Option Type Description
:applies_to_children Specify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).
:applies_to_self Indicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.
:one_level_deep Indicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
end

or:

rights :read, ['Administrators','Everyone']
rights :full_control, 'Users', :applies_to_children => true
rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true

Some other important things to know when using the rights attribute:

  • Only inherited rights remain. All existing explicit rights on the object are removed and replaced.
  • If rights are not specified, nothing will be changed. The chef-client does not clear out the rights on a file or directory if rights are not specified.
  • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration.

Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
  deny_rights :read, ['Julian', 'Lewis']
end

or:

deny_rights :full_control, ['Sally']

Inheritance

By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The inherits property can be used to specifically tell the chef-client to apply (or not apply) inherited rights from its parent directory.

For example, the following example specifies the rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
end

and then the following example specifies how to use inheritance to deny access to the child directory:

directory 'C:\mordor\mount_doom' do
  rights :full_control, 'MORDOR\Sauron'
  inherits false # Sauron is the only person who should have any sort of access
end

If the deny_rights permission were to be used instead, something could slip through unless all users and groups were denied.

Another example also shows how to specify rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
  rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there
end

but then not use the inherits property to deny those rights on a child directory:

directory 'C:\mordor\mount_doom' do
  deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough
end

Because the inherits property is not specified, the chef-client will default it to true, which will ensure that security settings for existing files remain unchanged.

File Specificity

A cookbook is frequently designed to work across many platforms and is often required to distribute a specific file to a specific platform. A cookbook can be designed to support the distribution of files across platforms, while ensuring that the correct file ends up on each system.

The pattern for file specificity depends on two things: the lookup path and the source attribute. The first pattern that matches is used:

  1. /host-$fqdn/$source
  2. /$platform-$platform_version/$source
  3. /$platform/$source
  4. /default/$source
  5. /$source

Use an array with the source attribute to define an explicit lookup path. For example:

file '/conf.py' do
  source ['#{node.chef_environment}.py', 'conf.py']
end

The following example emulates the entire file specificity pattern by defining it as an explicit path:

file '/conf.py' do
  source %W{
    host-#{node['fqdn']}/conf.py
    #{node['platform']}-#{node['platform_version']}/conf.py
    #{node['platform']}/conf.py
    default/conf.py
  }
end

A cookbook may have a /files directory structure like this:

files/
   host-foo.example.com
   ubuntu-10.04
   ubuntu-10
   ubuntu
   redhat-5.8
   redhat-6.4
   ...
   default

and a resource that looks something like the following:

cookbook_file '/usr/local/bin/apache2_module_conf_generate.pl' do
  source 'apache2_module_conf_generate.pl'
  mode '0755'
  owner 'root'
  group 'root'
end

This resource is matched in the same order as the /files directory structure. For a node that is running Ubuntu 10.04, the second item would be the matching item and the location to which the file identified in the cookbook_file resource would be distributed:

host-foo.example.com/apache2_module_conf_generate.pl
ubuntu-10.04/apache2_module_conf_generate.pl
ubuntu-10/apache2_module_conf_generate.pl
ubuntu/apache2_module_conf_generate.pl
default/apache2_module_conf_generate.pl

If the apache2_module_conf_generate.pl file was located in the cookbook directory under files/host-foo.example.com/, the specified file(s) would only be copied to the machine with the domain name foo.example.com.

Host Notation

The naming of folders within cookbook directories must literally match the host notation used for file specificity matching. For example, if a host is named foo.example.com, the folder must be named host-foo.example.com.

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.

Transfer a file

cookbook_file 'file.txt' do
  mode '0755'
end

Handle cookbook_file and yum_package resources in the same recipe

When a cookbook_file resource and a yum_package resource are both called from within the same recipe, use the flush_cache attribute to dump the in-memory Yum cache, and then use the repository immediately to ensure that the correct package is installed:

cookbook_file '/etc/yum.repos.d/custom.repo' do
  source 'custom'
  mode '0755'
end

yum_package 'only-in-custom-repo' do
  action :install
  flush_cache [ :before ]
end

Install repositories from a file, trigger a command, and force the internal cache to reload

The following example shows how to install new Yum repositories from a file, where the installation of the repository triggers a creation of the Yum cache that forces the internal cache for the chef-client to reload:

execute 'create-yum-cache' do
 command 'yum -q makecache'
 action :nothing
end

ruby_block 'reload-internal-yum-cache' do
  block do
    Chef::Provider::Package::Yum::YumCache.instance.reload
  end
  action :nothing
end

cookbook_file '/etc/yum.repos.d/custom.repo' do
  source 'custom'
  mode '0755'
  notifies :run, 'execute[create-yum-cache]', :immediately
  notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately
end

Use a case statement

The following example shows how a case statement can be used to handle a situation where an application needs to be installed on multiple platforms, but where the install directories are different paths, depending on the platform:

cookbook_file 'application.pm' do
  path case node['platform']
    when 'centos','redhat'
      '/usr/lib/version/1.2.3/dir/application.pm'
    when 'arch'
      '/usr/share/version/core_version/dir/application.pm'
    else
      '/etc/version/dir/application.pm'
    end
  source "application-#{node['languages']['perl']['version']}.pm"
  owner 'root'
  group 'root'
  mode '0755'
end

Manage dotfiles

The following example shows using the directory and cookbook_file resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to:

"files": {
  ".zshrc": {
    "mode": '0755',
    "source": "dot-zshrc"
    },
  ".bashrc": {
    "mode": '0755',
    "source": "dot-bashrc"
     },
  ".bash_profile": {
    "mode": '0755',
    "source": "dot-bash_profile"
    },
  }

and then the following resources manage the dotfiles:

if u.has_key?('files')
  u['files'].each do |filename, file_data|

  directory "#{home_dir}/#{File.dirname(filename)}" do
    recursive true
    mode '0755'
  end if file_data['subdir']

  cookbook_file "#{home_dir}/#{filename}" do
    source "#{u['id']}/#{file_data['source']}"
    owner 'u['id']'
    group 'group_id'
    mode 'file_data['mode']'
    ignore_failure true
    backup 0
  end
end

cron

[edit on GitHub]

Use the cron resource to manage cron entries for time-based job scheduling. Properties for a schedule will default to * if not provided. The cron resource requires access to a crontab program, typically cron.

Warning

The cron resource should only be used to modify an entry in a crontab file. Use the cookbook_file or template resources to add a crontab file to the cron.d directory. The cron_d lightweight resource (found in the cron cookbook) is another option for managing crontab files.

Syntax

A cron resource block manage cron entries. For example, to get a weekly cookbook report from the Chef Supermarket:

cron 'cookbooks_report' do
  action node.tags.include?('cookbooks-report') ? :create : :delete
  minute '0'
  hour '0'
  weekday '1'
  user 'getchef'
  mailto 'sysadmin@example.com'
  home '/srv/supermarket/shared/system'
  command %W{
    cd /srv/supermarket/current &&
    env RUBYLIB="/srv/supermarket/current/lib"
    RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}"
    bundle exec rake cookbooks_report
  }.join(' ')
end

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

cron 'name' do
  command                    String
  day                        String
  environment                Hash
  home                       String
  hour                       String
  mailto                     String
  minute                     String
  month                      String
  notifies                   # see description
  path                       String
  provider                   Chef::Provider::Cron
  shell                      String
  subscribes                 # see description
  time                       Symbol
  user                       String
  weekday                    String, Symbol
  action                     Symbol # defaults to :create if not specified
end

where

  • cron is the resource
  • name is the name of the resource block
  • command is the command to be run
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • command, day, environment, home, hour, mailto, minute, month, path, provider, shell, time, user, and weekday 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

This resource has the following actions:

:create
Default. Create an entry in a cron table file (crontab). If an entry already exists (but does not match), update that entry to match.
:delete
Delete an entry from a cron table file (crontab).
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.

Properties

This resource has the following properties:

command

Ruby Type: String

The command to be run, or the path to a file that contains the command to be run.

Some examples:

command if [ -x /usr/share/mdadm/checkarray ] && [ $(date +\%d) -le 7 ];
then /usr/share/mdadm/checkarray --cron --all --idle --quiet; fi

and:

command %w{
  cd /srv/opscode-community-site/current &&
  env RUBYLIB="/srv/opscode-community-site/current/lib"
  RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}"
  bundle exec rake cookbooks_report
}.join(' ')

and:

command "/srv/app/scripts/daily_report"
day

Ruby Type: String

The day of month at which the cron entry should run (1 - 31). Default value: *.

environment

Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

home

Ruby Type: String

Set the HOME environment variable.

hour

Ruby Type: String

The hour at which the cron entry is to run (0 - 23). Default value: *.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

mailto

Ruby Type: String

Set the MAILTO environment variable.

minute

Ruby Type: String

The minute at which the cron entry should run (0 - 59). Default value: *.

month

Ruby Type: String

The month in the year on which a cron entry is to run (1 - 12). Default value: *.

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 notifiy 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 very 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
path

Ruby Type: String

Set the PATH environment variable.

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

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.

shell

Ruby Type: String

Set the SHELL environment variable.

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.

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 very 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
time

Ruby Type: Symbol

A time interval. Possible values: :annually, :daily, :hourly, :midnight, :monthly, :reboot, :weekly, or :yearly.

user

Ruby Type: String

This attribute is not applicable on the AIX platform. The name of the user that runs the command. If the user property is changed, the original user for the crontab program continues to run until that crontab program is deleted. Default value: root.

weekday

Ruby Type: String

The day of the week on which this entry is to run (0 - 6), where Sunday = 0. Default value: *.

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.

Run a program at a specified interval

cron 'noop' do
  hour '5'
  minute '0'
  command '/bin/true'
end

Run an entry if a folder exists

cron 'ganglia_tomcat_thread_max' do
  command "/usr/bin/gmetric
    -n 'tomcat threads max'
    -t uint32
    -v '/usr/local/bin/tomcat-stat
    --thread-max'"
  only_if do File.exist?('/home/jboss') end
end

Run every Saturday, 8:00 AM

The following example shows a schedule that will run every hour at 8:00 each Saturday morning, and will then send an email to “admin@example.com” after each run.

cron 'name_of_cron_entry' do
  minute '0'
  hour '8'
  weekday '6'
  mailto 'admin@example.com'
  action :create
end

Run only in November

The following example shows a schedule that will run at 8:00 PM, every weekday (Monday through Friday), but only in November:

cron 'name_of_cron_entry' do
  minute '0'
  hour '20'
  day '*'
  month '11'
  weekday '1-5'
  action :create
end

csh

[edit on GitHub]

Use the csh resource to execute scripts using the csh interpreter. This resource may also use any of the actions and properties that are available to the execute resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Note

The csh script resource (which is based on the script resource) is different from the ruby_block resource because Ruby code that is run with this resource is created as a temporary file and executed like other script resources, rather than run inline.

Syntax

A csh resource block executes scripts using csh:

csh 'hello world' do
  code <<-EOH
    echo "Hello world!"
    echo "Current directory: " $cwd
    EOH
end

where

  • code specifies the command to run

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

csh 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  notifies                   # see description
  path                       Array
  provider                   Chef::Provider::Script::Csh
  returns                    Integer, Array
  subscribes                 # see description
  timeout                    Integer, Float
  user                       String, Integer
  umask                      String, Integer
  action                     Symbol # defaults to :run if not specified
end

where

  • csh is the resource
  • name is the name of the resource block
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • code, creates, cwd, environment, flags, group, path, provider, returns, timeout, user, and umask 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

This resource has the following actions:

:nothing
Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it.
:run
Default. Run a script.

Properties

This resource has the following properties:

code

Ruby Type: String

A quoted (” ”) string of code to be executed.

creates

Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd

Ruby Type: String

The current working directory.

environment

Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags

Ruby Type: String

One or more command line flags that are passed to the interpreter when a command is invoked.

group

Ruby Types: String, Integer

The group name or group ID that must be changed before running a command.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

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 notifiy 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 very 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
path

Ruby Type: Array

An array of paths to use when searching for a command. These paths are not added to the command’s environment $PATH. The default value uses the system path.

Warning

For example:

csh 'mycommand' do
  environment 'PATH' => "/my/path/to/bin:#{ENV['PATH']}"
end
provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

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.

returns

Ruby Types: Integer, Array

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. Default value: 0.

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.

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 very 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
timeout

Ruby Types: Integer, Float

The amount of time (in seconds) a command is to wait before timing out. Default value: 3600.

user

Ruby Types: String, Integer

The user name or user ID that should be changed before running a command.

umask

Ruby Types: String, Integer

The file mode creation mask, or umask.

Guards

A guard property can be used to evaluate the state of a node during the execution phase of the chef-client run. Based on the results of this evaluation, a guard property is then used to tell the chef-client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 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.
  • A block is executed as Ruby code that must return either 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 the chef-client to do nothing.

Attributes

The following properties can be used to define a guard that is evaluated during the execution phase of the chef-client run:

not_if
Prevent a resource from executing when the condition returns true.
only_if
Allow a resource to execute only if the condition returns true.

Arguments

The following arguments can be used with the not_if or only_if guard properties:

:user

Specify the user that a command will run as. For example:

not_if 'grep adam /etc/passwd', :user => 'adam'
:group

Specify the group that a command will run as. For example:

not_if 'grep adam /etc/passwd', :group => 'adam'
:environment

Specify a Hash of environment variables to be set. For example:

not_if 'grep adam /etc/passwd', :environment => {
  'HOME' => '/home/adam'
}
:cwd

Set the current working directory before running a command. For example:

not_if 'grep adam passwd', :cwd => '/etc'
:timeout

Set a timeout for a command. For example:

not_if 'sleep 10000', :timeout => 10

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Script, script
When this short name is used, the chef-client will determine the correct provider during the chef-client run.
Chef::Provider::Script::Csh, csh
The provider for the csh command interpreter.

Examples

None.

deploy

[edit on GitHub]

Use the deploy resource to manage and control deployments. This is a popular resource, but is also complex, having the most properties, multiple providers, the added complexity of callbacks, plus four attributes that support layout modifications from within a recipe.

The deploy resource is modeled after Capistrano, a utility and framework for executing commands in parallel on multiple remote machines via SSH. The deploy resource is designed to behave in a way that is similar to the deploy and deploy:migration tasks in Capistrano.

Syntax

A deploy resource block manages and controls deployments:

deploy 'private_repo' do
  repo 'git@github.com:acctname/private-repo.git'
  user 'ubuntu'
  deploy_to '/tmp/private_code'
  ssh_wrapper '/tmp/private_code/wrap-ssh4git.sh'
  action :deploy
end

For example, an application that is deployed to a folder named "/path/to/application":

deploy_revision '/path/to/application' do
  repo 'ssh://name-of-git-repo/repos/repo.git'
  migrate false
  purge_before_symlink %w{one two folder/three}
  create_dirs_before_symlink []
  symlinks{
    "one"   => "one",
    "two"   => "two",
    "three" => "folder/three"
  }
  before_restart do
    # some Ruby code
  end
  notifies :restart, 'service[foo]'
  notifies :restart, 'service[bar]'
end

For the example shown above:

  • Because an action is not explicitly specified, the chef-client will use the default action: :deploy
  • The purge_before_symlink application layout is an array of paths that will be cleared before the symlinks property is run
  • The create_dirs_before_symlink property is empty, which is different from the default
  • The symlinks property is creating three symbolic links
  • The before_restart callback is being used to add custom actions that will occur at the end of the deployment process, but before any services have been notified
  • At the end, the recipe is using the notifies property—a common attribute available to all resources—to alert two services (named “foo” and “bar”) that they should restart.

The full syntax for all of the properties that are available to the deploy when used with git is:

deploy 'name' do
  after_restart              Proc, String
  before_migrate             Proc, String
  before_restart             Proc, String
  before_symlink             Proc, String
  branch                     String
  create_dirs_before_symlink Array
  deploy_to                  String # defaults to 'name' if not specified
  depth                      Integer
  enable_submodules          TrueClass, FalseClass
  environment                Hash
  git_ssh_wrapper            String
  group                      String
  keep_releases              Integer
  migrate                    TrueClass, FalseClass
  migration_command          String
  notifies                   # see description
  provider                   Chef::Provider::Deploy
  purge_before_symlink       Array
  remote                     String
  repo                       String
  repository                 String
  repository_cache           String
  restart_command            Proc, String
  revision                   String
  rollback_on_error          TrueClass, FalseClass
  scm_provider               Chef::Provider::Git
  shallow_clone              TrueClass, FalseClass
  ssh_wrapper                String
  symlinks                   Hash
  symlink_before_migrate     Hash
  timeout                    Integer
  user                       String
  action                     Symbol # defaults to :create if not specified
end

and the full syntax for all of the properties that are available to the deploy when used with Subversion is:

deploy 'name' do
  after_restart              Proc, String
  before_migrate             Proc, String
  before_restart             Proc, String
  before_symlink             Proc, String
  branch                     String
  create_dirs_before_symlink Array
  deploy_to                  String # defaults to 'name' if not specified
  environment                Hash
  group                      String
  keep_releases              Integer
  migrate                    TrueClass, FalseClass
  migration_command          String
  notifies                   # see description
  provider                   Chef::Provider::Deploy
  purge_before_symlink       Array
  repo                       String
  repository                 String
  repository_cache           String
  restart_command            Proc, String
  revision                   String
  rollback_on_error          TrueClass, FalseClass
  scm_provider               Chef::Provider::Subversion
  subscribes                 # see description
  svn_arguments              String
  svn_password               String
  svn_username               String
  symlinks                   Hash
  symlink_before_migrate     Hash
  timeout                    Integer
  user                       String
  action                     Symbol # defaults to :create if not specified
end

where

  • deploy is the resource
  • name is the name of the resource block
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • after_restart, before_migrate, before_restart, before_symlink, branch, create_dirs_before_symlink, deploy_to, depth, enable_submodules, environment, git_ssh_wrapper, group, keep_releases, migrate, migration_command, provider, purge_before_symlink, remote, repo, repository, repository_cache, restart_command, revision, rollback_on_error, scm_provider, shallow_clone, ssh_wrapper, svn_arguments, svn_password, svn_username, symlinks, symlink_before_migrate, timeout, and user 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.

Deploy Strategies

In the deploy directory, a sub-directory named shared must be created. This sub-directory is where configuration and temporary files will be kept. A typical Ruby on Rails application will have config, log, pids, and system directories within the shared directory to keep the files stored there independent of the code in the source repository.

In addition to the shared sub-directory, the deploy process will create sub-directories named releases and current (also in the deploy directory). The release directory holds (up to) five most recently deployed versions of an application. The current directory holds the currently-released version.

For example:

deploy_directory/
  current/
  releases/
  shared/
    config/
    log/
    pids/
    system/

Deploy Phases

A deployment happens in four phases:

  1. Checkout—the chef-client uses the scm resource to get the specified application revision, placing a clone or checkout in the sub-directory of the deploy directory named cached-copy. A copy of the application is then placed in a sub-directory under releases.
  2. Migrate—If a migration is to be run, the chef-client symlinks the database configuration file into the checkout (config/database.yml by default) and runs the migration command. For a Ruby on Rails application, the migration_command is usually set to rake db:migrate.
  3. Symlink—Directories for shared and temporary files are removed from the checkout (log, tmp/pids, and public/system by default). After this step, any needed directories (tmp, public, and config by default) are created if they don’t already exist. This step is completed by symlinking shared directories into the current release, public/system, tmp/pids, and log directories, and then symlinking the release directory to current.
  4. Restart—The application is restarted according to the restart command set in the recipe.
Deploy Cache File

The chef-client uses a cache file to keep track of the order in which each revision of an application is deployed. By default, the cache file is located at /var/chef/cache/revision-deploys/APPNAME/. To force a re-deploy, delete the deployment directory or delete the cache file.

Callbacks

In-between each step in a deployment process, callbacks can be run using arbitrary Ruby code, including recipes. All callbacks support embedded recipes given in a block, but each callback assumes a shell command (instead of a deploy hook filename) when given a string.

The following callback types are available:

Callback Description
after_restart A block of code, or a path to a file that contains code, that is run after restarting. Default value: deploy/after_restart.rb.
before_migrate A block of code, or a path to a file that contains code, that is run before a migration. Default value: deploy/before_migrate.rb.
before_restart A block of code, or a path to a file that contains code, that is run before restarting. Default value: deploy/before_restart.rb.
before_symlink A block of code, or a path to a file that contains code, that is run before symbolic linking. Default value: deploy/before_symlink.rb.

Each of these callback types can be used in one of three ways:

  • To pass a block of code, such as Ruby or Python
  • To specify a file
  • To do neither; the chef-client will look for a callback file named after one of the callback types (before_migrate.rb, for example) and if the file exists, to evaluate it as if it were a specified file

Within a callback, there are two ways to get access to information about the deployment:

  • release_path can be used to get the path to the current release
  • new_resource can be used to access the deploy resource, including environment variables that have been set there (using new_resource is a preferred approach over using the @configuration variable)

Both of these options must be available at the top-level within the callback, along with any assigned values that will be used later in the callback.

Callbacks and Capistrano

If you are familiar with Capistrano, the following examples should help you know when to use the various callbacks that are available. If you are not familiar with Capistrano, then follow the semantic names of these callbacks to help you determine when to use each of the callbacks within a recipe that is built with the deploy resource.

The following example shows where callbacks fit in relation to the steps taken by the deploy process in Capistrano:

_images/includes_resource_deploy_strategy_callbacks_example1.png

and the following example shows the same comparison, but with the deploy:migrations process:

_images/includes_resource_deploy_strategy_callbacks_example2.png

Layout Modifiers

The deploy resource expects an application to be structured like a Ruby on Rails application, but the layout can be modified to meet custom requirements as needed. Use the following attributes within a recipe to modify the layout of a recipe that is using the deploy resource:

Layout Modifiers Description
create_dirs_before_symlink Create directories in the release directory before symbolic links are created. This property runs after purge_before_symlink and before symlink.
purge_before_symlink An array of directories (relative to the application root) to be removed from a checkout before symbolic links are created. This attribute runs before create_dirs_before_symlink and before symlink.
symlink_before_migrate Map files in a shared directory to the current release directory. The symbolic links for these files are created before any migration is run. Use parentheses ( ) around curly braces { } to ensure the contents within the curly braces are interpreted as a block and not as an empty Hash. Set to symlink_before_migrate({}) to prevent the creation of symbolic links.
symlinks Map files in a shared directory to their paths in the current release directory. This property runs after create_dirs_before_symlink and purge_before_symlink.

Actions

This resource has the following actions:

:deploy
Default. Deploy an application.
:force_deploy
Remove any existing release of the same code version and re-deploy a new one in its place.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:rollback
Roll an application back to the previous release.

Naming Resources

The chef-client caches deployment actions as they are taken. In order for the chef-client to be able to apply a subsequent deployment action—rolling back a release using the :rollback action, for example—all related deployment actions must be contained within resource blocks that have the same name. This ensures that the chef-client will be able to find the correct deployment from within the cached deployment actions.

For example, a simple deployment:

deploy_revision 'name' do
  ...
  action :deploy
end

In order to use the :rollback action with this deployment, the :rollback action must be in a resource block that has the same resource name as the initial deploy action. For example:

deploy_revision 'name' do
  ...
  action :rollback
end

Properties

This resource has the following properties:

after_restart

Ruby Types: Proc, String

A block of code, or a path to a file that contains code, that is run after restarting. Default value: deploy/after_restart.rb.

before_migrate

Ruby Types: Proc, String

A block of code, or a path to a file that contains code, that is run before a migration. Default value: deploy/before_migrate.rb.

before_restart

Ruby Types: Proc, String

A block of code, or a path to a file that contains code, that is run before restarting. Default value: deploy/before_restart.rb.

before_symlink

Ruby Types: Proc, String

A block of code, or a path to a file that contains code, that is run before symbolic linking. Default value: deploy/before_symlink.rb.

branch

Ruby Type: String

The alias for the revision.

create_dirs_before_symlink

Ruby Type: Array

Create directories in the release directory before symbolic links are created. This property runs after purge_before_symlink and before symlink. Default value: %w{tmp public config} (or the same as ["tmp", "public", "config"]).

deploy_to

Ruby Type: String

The “meta root” for the application, if different from the path that is used to specify the name of a resource. Default value: the name of the resource block See “Syntax” section above for more information.

environment

Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

group

Ruby Type: String

The system group that is responsible for the checked-out code.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

keep_releases

Ruby Type: Integer

The number of releases for which a backup is kept. Default value: 5.

migrate

Ruby Types: TrueClass, FalseClass

Run a migration command. Default value: false.

migration_command

Ruby Type: String

A string that contains a shell command that can be executed to run a migration operation.

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 notifiy 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 very 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
provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

purge_before_symlink

Ruby Type: Array

An array of directories (relative to the application root) to be removed from a checkout before symbolic links are created. This attribute runs before create_dirs_before_symlink and before symlink. Default value: %w{log tmp/pids public/system} (or the same as ["log", "tmp/pids", "public/system"].

repo

Ruby Type: String

The alias for the repository.

repository

Ruby Type: String

The URI for the repository.

repository_cache

Ruby Type: String

The name of the sub-directory in which the pristine copy of an application’s source is kept. Default value: cached-copy.

restart_command

Ruby Types: String, Proc

A string that contains a shell command that can be executed to run a restart operation.

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.

revision

Ruby Type: String

A branch, tag, or commit to be synchronized with git. This can be symbolic, like HEAD or it can be a source control management-specific revision identifier. Default value: HEAD.

rollback_on_error

Ruby Types: TrueClass, FalseClass

Roll a resource back to a previously-deployed release if an error occurs when deploying a new release. Default value: false.

scm_provider

Ruby Type: Chef Class

The name of the source control management provider. Default value: Chef::Provider::Git. Optional values: Chef::Provider::Subversion.

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.

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 very 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
symlinks

Ruby Type: Hash

Map files in a shared directory to their paths in the current release directory. This property runs after create_dirs_before_symlink and purge_before_symlink. Default value: {"system" => "public/system", "pids" => "tmp/pids", "log" => "log"}.

symlink_before_migrate

Ruby Type: Hash

Map files in a shared directory to the current release directory. The symbolic links for these files are created before any migration is run. Use parentheses ( ) around curly braces { } to ensure the contents within the curly braces are interpreted as a block and not as an empty Hash. Set to symlink_before_migrate({}) to prevent the creation of symbolic links. Default value: {"config/database.yml" => "config/database.yml"}.

timeout

Ruby Type: Integer

The amount of time (in seconds) to wait for a command to execute before timing out. When specified, this value is passed from the deploy resource to the git or subversion resources.

user

Ruby Type: String

The system user that is responsible for the checked-out code.

The following properties are for use with git only:

depth

Ruby Type: Integer

The depth of a git repository, truncated to the specified number of revisions. See shallow_clone.

enable_submodules

Ruby Types: TrueClass, FalseClass

Perform a sub-module initialization and update. Default value: false.

git_ssh_wrapper

Ruby Type: String

The alias for the ssh_wrapper.

remote

Ruby Type: String

The remote repository to use when synchronizing an existing clone. Default value: origin.

shallow_clone

Ruby Types: TrueClass, FalseClass

Set the clone depth to 5. If a depth other than 5 is required, use the depth property instead of shallow_clone. Default value: false.

ssh_wrapper

Ruby Type: String

The path to the wrapper script used when running SSH with git. The GIT_SSH environment variable is set to this.

The following properties are for use with Subversion only:

svn_arguments

Ruby Type: String

The extra arguments that are passed to the Subversion command.

svn_password

Ruby Type: String

The password for a user that has access to the Subversion repository.

svn_username

Ruby Type: String

The user name for a user that has access to the Subversion repository.

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Deploy, deploy
When this short name is used, the chef-client will determine the correct provider during the chef-client run.
Chef::Provider::Deploy::Branch, deploy_branch
See below for more information.
Chef::Provider::Deploy::Revision, deploy_revision
See below for more information.
Chef::Provider::Deploy::TimestampedDeploy, timestamped_deploy
The default provider for all platforms. See below for more information.

deploy_branch

The deploy_branch resource functions identically to the deploy_revision resource, in terms of how the chef-client processes the resource during the chef-client run. It uses the same Deploy::Revision provider, the same set of actions and attributes, and is (outside of the name itself) identical to the deploy_revision resource. Using the deploy_revision resource is preferred; however, the deploy_branch resource exists for those situations where, semantically, it is preferable to refer to a resource as a “branch” instead of a “revision”.

deploy_revision

The deploy_revision provider is the recommended provider, even if it is not listed as the default. The deploy_revision provider is used to ensure that the name of a release sub-directory is based on a revision identifier. For users of git, this will be the familiar SHA checksum. For users of Subversion, it will be the integer revision number. If a name other than a revision identifier is provided—branch names, tags, and so on—the chef-client will ignore the alternate names and will look up the revision identifier and use it to name the release sub-directory. When the deploy_revision provider is given an exact revision to deploy, it will behave in an idempotent manner.

The deploy_revision provider results in deployed components under the destination location that is owned by the user who runs the application. This is sometimes an issue for certain workflows. If issues arise, consider the following:

  • Incorporate changing permissions to the desired end state from within a recipe
  • Add a before_restart block to fix up the permissions
  • Have an unprivileged user (for example: opscode) be the owner of the deploy directory and another unprivileged user (for example: opscodeapp) run the application. Most often, this is the solution that works best

When using the deploy_revision provider, and when the deploy fails for any reason, and when the same code is used to re-deploy, the action should be set manually to :force_deploy. Forcing the re-deploy will remove the old release directory, after which the deploy can proceed as usual. (Forcing a re-deploy over the current release can cause some downtime.) Deployed revisions are stored in (file_cache_path)/revision-deploys/(deploy_path).

timestamped_deploy

The timestamped_deploy provider is the default deploy provider. It is used to name release directories with a timestamp in the form of YYYYMMDDHHMMSS. For example: /my/deploy/dir/releases/20121120162342. The deploy resource will determine whether or not to deploy code based on the existence of the release directory in which it is attempting to deploy. Because the timestamp is different for every chef-client run, the timestamped_deploy provider is not idempotent. When the timestamped_deploy provider is used, it requires that the action setting on a resource be managed manually in order to prevent unintended continuous deployment.

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.

Modify the layout of a Ruby on Rails application

The layout of the deploy resource matches a Ruby on Rails app by default, but this can be customized. To customize the layout, do something like the following:

deploy '/my/apps/dir/deploy' do
  # Use a local repo if you prefer
  repo '/path/to/gitrepo/typo/'
  environment 'RAILS_ENV' => 'production'
  revision 'HEAD'
  action :deploy
  migration_command 'rake db:migrate --trace'
  migrate true
  restart_command 'touch tmp/restart.txt'
  create_dirs_before_symlink  %w{tmp public config deploy}

  # You can use this to customize if your app has extra configuration files
  # such as amqp.yml or app_config.yml
  symlink_before_migrate  'config/database.yml' => 'config/database.yml'

  # If your app has extra files in the shared folder, specify them here
  symlinks  'system' => 'public/system',
            'pids' => 'tmp/pids',
            'log' => 'log',
            'deploy/before_migrate.rb' => 'deploy/before_migrate.rb',
            'deploy/before_symlink.rb' => 'deploy/before_symlink.rb',
            'deploy/before_restart.rb' => 'deploy/before_restart.rb',
            'deploy/after_restart.rb' => 'deploy/after_restart.rb'
end

Use resources within callbacks

Using resources from within your callbacks as blocks or within callback files distributed with your application’s source code. To use embedded recipes for callbacks:

deploy "#{node['tmpdir']}/deploy" do
  repo "#{node['tmpdir']}/gitrepo/typo/"
  environment 'RAILS_ENV' => 'production'
  revision 'HEAD'
  action :deploy
  migration_command 'rake db:migrate --trace'
  migrate true

  # Callback awesomeness:
  before_migrate do
    current_release = release_path

    directory "#{current_release}/deploy" do
      mode '0755'
    end

    # creates a callback for before_symlink
    template "#{current_release}/deploy/before_symlink_callback.rb" do
      source 'embedded_recipe_before_symlink.rb.erb'
      mode '0755'
    end

  end

  # This file can contain Chef recipe code, plain ruby also works
  before_symlink 'deploy/before_symlink_callback.rb'

  restart do
    current_release = release_path
    file "#{release_path}/tmp/restart.txt" do
      mode '0755'
    end
  end

end

Deploy from a private git repository without using the application cookbook

To deploy from a private git repository without using the application cookbook, first ensure that:

  • the private key does not have a passphrase, as this will pause a chef-client run to wait for input
  • an SSH wrapper is being used
  • a private key has been added to the node

and then remove a passphrase from a private key by using code similar to:

ssh-keygen -p -P 'PASSPHRASE' -N '' -f id_deploy

Use an SSH wrapper

To write a recipe that uses an SSH wrapper:

  1. Create a file in the cookbooks/COOKBOOK_NAME/files/default directory that is named wrap-ssh4git.sh and which contains the following:

    #!/usr/bin/env bash
    /usr/bin/env ssh -o "StrictHostKeyChecking=no" -i "/tmp/private_code/.ssh/id_deploy" $1 $2
    
  2. Set up the cookbook file.

  3. Add a recipe to the cookbook file similar to the following:

    directory '/tmp/private_code/.ssh' do
      owner 'ubuntu'
      recursive true
    end
    
    cookbook_file '/tmp/private_code/wrap-ssh4git.sh' do
      source 'wrap-ssh4git.sh'
      owner 'ubuntu'
      mode '0755'
    end
    
    deploy 'private_repo' do
      repo 'git@github.com:acctname/private-repo.git'
      user 'ubuntu'
      deploy_to '/tmp/private_code'
      action :deploy
      ssh_wrapper '/tmp/private_code/wrap-ssh4git.sh'
    end
    

    This will deploy the git repository at git@github.com:acctname/private-repo.git in the /tmp/private_code directory.

Use a callback to include a file that will be passed as a code block

The code in a file that is included in a recipe using a callback is evaluated exactly as if the code had been put in the recipe as a block. Files are searched relative to the current release.

To specify a file that contains code to be used as a block:

deploy '/deploy/dir/' do
  # ...

  before_migrate 'callbacks/do_this_before_migrate.rb'
end

Use a callback to pass a code block

To pass a block of Python code before a migration is run:

deploy_revision '/deploy/dir/' do
  # other attributes
  # ...

  before_migrate do
    # release_path is the path to the timestamp dir
    # for the current release
    current_release = release_path

    # Create a local variable for the node so we'll have access to
    # the attributes
    deploy_node = node

    # A local variable with the deploy resource.
    deploy_resource = new_resource

    python do
      cwd current_release
      user 'myappuser'
      code<<-PYCODE
        # Woah, callbacks in python!
        # ...
        # current_release, deploy_node, and deploy_resource are all available
        # within the deploy hook now.
      PYCODE
    end
  end
end

Use the same API for all recipes using the same gem

Any recipes using the git-deploy gem can continue using the same API. To include this behavior in a recipe, do something like the following:

deploy "/srv/#{appname}" do
  repo 'git://github.com/radiant/radiant.git'
  revision 'HEAD'
  user 'railsdev'
  enable_submodules false
  migrate true
  migration_command 'rake db:migrate'
  # Giving a string for environment sets RAILS_ENV, MERB_ENV, RACK_ENV
  environment 'production'
  shallow_clone true
  action :deploy
  restart_command 'touch tmp/restart.txt'
end

Deploy without creating symbolic links to a shared folder

To deploy without creating symbolic links to a shared folder:

deploy '/my/apps/dir/deploy' do
  symlinks {}
end

When deploying code that is not Ruby on Rails and symbolic links to a shared folder are not wanted, use parentheses () or Hash.new to avoid ambiguity. For example, using parentheses:

deploy '/my/apps/dir/deploy' do
  symlinks({})
end

or using Hash.new:

deploy '/my/apps/dir/deploy' do
  symlinks Hash.new
end

Clear a layout modifier attribute

Using the default property values for the various resources is the recommended starting point when working with recipes. Then, depending on what each node requires, these default values can be overridden with node-, role-, environment-, and cookbook-specific values. The deploy resource has four layout modifiers: create_dirs_before_symlink, purge_before_symlink, symlink_before_migrate, and symlinks. Each of these is a Hash that behaves as a property of the deploy resource. When these layout modifiers are used in a recipe, they appear similar to the following:

deploy 'name' do
  ...
  symlink_before_migrate       {'config/database.yml' => 'config/database.yml'}
  create_dirs_before_symlink   %w{tmp public config}
  purge_before_symlink         %w{log tmp/pids public/system}
  symlinks                     { 'system' => 'public/system',
                                 'pids' => 'tmp/pids',
                                 'log' => 'log'
                               }
  ...
end

and then what these layout modifiers look like if they were empty:

deploy 'name' do
  ...
  symlink_before_migrate       nil
  create_dirs_before_symlink   []
  purge_before_symlink         []
  symlinks                     nil
  ...
end

In most cases, using the empty values for the layout modifiers will prevent the chef-client from passing symbolic linking information to a node during the chef-client run. However, in some cases, it may be preferable to ensure that one (or more) of these layout modifiers do not pass any symbolic linking information to a node during the chef-client run at all. Because each of these layout modifiers are a Hash, the clear instance method can be used to clear out these values.

To clear the default values for a layout modifier:

deploy 'name' do
  ...
  symlink_before_migrate.clear
  create_dirs_before_symlink.clear
  purge_before_symlink.clear
  symlinks.clear
  ...
end

In general, use this approach carefully and only after it is determined that nil or empty values won’t provide the expected result.

directory

[edit on GitHub]

Use the directory resource to manage a directory, which is a hierarchy of folders that comprises all of the information stored on a computer. The root directory is the top-level, under which the rest of the directory is organized. The directory resource uses the name property to specify the path to a location in a directory. Typically, permission to access that location in the directory is required.

Syntax

A directory resource block declares a directory and the permissions needed on that directory. For example:

directory '/etc/apache2' do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

where

  • '/etc/apache2' specifies the directory
  • owner, group, and mode define the permissions

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

directory 'name' do
  group                      String, Integer
  inherits                   TrueClass, FalseClass
  mode                       String, Integer
  notifies                   # see description
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  provider                   Chef::Provider::Directory
  recursive                  TrueClass, FalseClass
  rights                     Hash
  subscribes                 # see description
  action                     Symbol # defaults to :create if not specified
end

where

  • directory 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
  • group, inherits, mode, owner, path, provider, recursive, and rights 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

This resource has the following actions:

:create
Default. Create a directory. If a directory already exists (but does not match), update that directory to match.
:delete
Delete a directory.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.

Properties

This resource has the following properties:

group

Ruby Types: Integer, String

A string or ID that identifies the group owner by group name, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

inherits

Ruby Types: TrueClass, FalseClass

Microsoft Windows only. Whether a file inherits rights from its parent directory. Default value: true.

mode

Ruby Types: Integer, String

A quoted 3-5 character string that defines the octal mode. For example: '755', '0755', or 00755. If mode is not specified and if the directory already exists, the existing mode on the directory is used. If mode is not specified, the directory does not exist, and the :create action is specified, the chef-client assumes a mask value of '0777', and then applies the umask for the system on which the directory is to be created to the mask value. For example, if the umask on a system is '022', the chef-client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

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 notifiy 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 very 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
owner

Ruby Types: Integer, String

A string or ID that identifies the group owner by user name, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path

Ruby Type: String

The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the name of the resource block See “Syntax” section above for more information.

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

recursive

Ruby Types: TrueClass, FalseClass

Create or delete parent directories recursively. For the owner, group, and mode properties, the value of this attribute applies only to the leaf directory. Default value: false.

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.

rights

Ruby Types: Integer, String

Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options.

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.

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 very 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

Recursive Directories

The directory resource can be used to create directory structures, as long as each directory within that structure is created explicitly. This is because the recursive attribute only applies group, mode, and owner attribute values to the leaf directory.

A directory structure:

/foo
  /bar
    /baz

The following example shows a way create a file in the /baz directory:

directory "/foo/bar/baz" do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

But with this example, the group, mode, and owner attribute values will only be applied to /baz. Which is fine, if that’s what you want. But most of the time, when the entire /foo/bar/baz directory structure is not there, you must be explicit about each directory. For example:

%w[ /foo /foo/bar /foo/bar/baz ].each do |path|
  directory path do
    owner 'root'
    group 'root'
    mode '0755'
  end
end

This approach will create the correct hierarchy—/foo, then /bar in /foo, and then /baz in /bar—and also with the correct attribute values for group, mode, and owner.

Windows File Security

To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes.

Access Control Lists (ACLs)

The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; the chef-client will apply them to the file or directory as required. The syntax for the rights property is as follows:

rights permission, principal, option_type => value

where

permission

Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control.

These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read.

(For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.)

principal
Use to specify a group or user name. This is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. The chef-client does not need to know if a principal is a user or a group.
option_type

A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types:

Option Type Description
:applies_to_children Specify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).
:applies_to_self Indicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.
:one_level_deep Indicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
end

or:

rights :read, ['Administrators','Everyone']
rights :full_control, 'Users', :applies_to_children => true
rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true

Some other important things to know when using the rights attribute:

  • Only inherited rights remain. All existing explicit rights on the object are removed and replaced.
  • If rights are not specified, nothing will be changed. The chef-client does not clear out the rights on a file or directory if rights are not specified.
  • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration.

Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
  deny_rights :read, ['Julian', 'Lewis']
end

or:

deny_rights :full_control, ['Sally']

Inheritance

By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The inherits property can be used to specifically tell the chef-client to apply (or not apply) inherited rights from its parent directory.

For example, the following example specifies the rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
end

and then the following example specifies how to use inheritance to deny access to the child directory:

directory 'C:\mordor\mount_doom' do
  rights :full_control, 'MORDOR\Sauron'
  inherits false # Sauron is the only person who should have any sort of access
end

If the deny_rights permission were to be used instead, something could slip through unless all users and groups were denied.

Another example also shows how to specify rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
  rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there
end

but then not use the inherits property to deny those rights on a child directory:

directory 'C:\mordor\mount_doom' do
  deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough
end

Because the inherits property is not specified, the chef-client will default it to true, which will ensure that security settings for existing files remain unchanged.

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.

Create a directory

directory '/tmp/something' do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

Create a directory in Microsoft Windows

directory "C:\\tmp\\something.txt" do
  rights :full_control, "DOMAIN\\User"
  inherits false
  action :create
end

or:

directory 'C:\tmp\something.txt' do
  rights :full_control, 'DOMAIN\User'
  inherits false
  action :create
end

Note

The difference between the two previous examples is the single- versus double-quoted strings, where if the double quotes are used, the backslash character (\) must be escaped using the Ruby escape character (which is a backslash).

Create a directory recursively

%w{dir1 dir2 dir3}.each do |dir|
  directory "/tmp/mydirs/#{dir}" do
    mode '0755'
    owner 'root'
    group 'root'
    action :create
    recursive true
  end
end

Delete a directory

directory '/tmp/something' do
  recursive true
  action :delete
end

Set directory permissions using a variable

The following example shows how read/write/execute permissions can be set using a variable named user_home, and then for owners and groups on any matching node:

user_home = "/#{node[:matching_node][:user]}"

directory user_home do
  owner 'node[:matching_node][:user]'
  group 'node[:matching_node][:group]'
  mode '0755'
  action :create
end

where matching_node represents a type of node. For example, if the user_home variable specified {node[:nginx]...}, a recipe might look similar to:

user_home = "/#{node[:nginx][:user]}"

directory user_home do
  owner 'node[:nginx][:user]'
  group 'node[:nginx][:group]'
  mode '0755'
  action :create
end

Set directory permissions for a specific type of node

The following example shows how permissions can be set for the /certificates directory on any node that is running Nginx. In this example, permissions are being set for the owner and group properties as root, and then read/write permissions are granted to the root.

directory "#{node[:nginx][:dir]}/shared/certificates" do
  owner 'root'
  group 'root'
  mode '0755'
  recursive true
end

Reload the configuration

The following example shows how to reload the configuration of a chef-client using the remote_file resource to:

  • using an if statement to check whether the plugins on a node are the latest versions
  • identify the location from which Ohai plugins are stored
  • using the notifies property and a ruby_block resource to trigger an update (if required) and to then reload the client.rb file.
directory 'node[:ohai][:plugin_path]' do
  owner 'chef'
  recursive true
end

ruby_block 'reload_config' do
  block do
    Chef::Config.from_file('/etc/chef/client.rb')
  end
  action :nothing
end

if node[:ohai].key?(:plugins)
  node[:ohai][:plugins].each do |plugin|
    remote_file node[:ohai][:plugin_path] +"/#{plugin}" do
      source plugin
      owner 'chef'
              notifies :run, 'ruby_block[reload_config]', :immediately
    end
  end
end

Manage dotfiles

The following example shows using the directory and cookbook_file resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to:

"files": {
  ".zshrc": {
    "mode": '0755',
    "source": "dot-zshrc"
    },
  ".bashrc": {
    "mode": '0755',
    "source": "dot-bashrc"
     },
  ".bash_profile": {
    "mode": '0755',
    "source": "dot-bash_profile"
    },
  }

and then the following resources manage the dotfiles:

if u.has_key?('files')
  u['files'].each do |filename, file_data|

  directory "#{home_dir}/#{File.dirname(filename)}" do
    recursive true
    mode '0755'
  end if file_data['subdir']

  cookbook_file "#{home_dir}/#{filename}" do
    source "#{u['id']}/#{file_data['source']}"
    owner 'u['id']'
    group 'group_id'
    mode 'file_data['mode']'
    ignore_failure true
    backup 0
  end
end

dpkg_package

[edit on GitHub]

Use the dpkg_package resource to manage packages for the dpkg platform. When a package is installed from a local file, it must be added to the node using the remote_file or cookbook_file resources.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, the chef-client will use details that are collected by Ohai at the start of the chef-client run to determine the correct package application. Using the package resource allows a recipe to be authored in a way that allows it to be used across many platforms.

Syntax

A dpkg_package resource block manages a package on a node, typically by installing it. The simplest use of the dpkg_package resource is:

dpkg_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

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

dpkg_package 'name' do
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  provider                   Chef::Provider::Package::Dpkg
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where

  • dpkg_package tells the chef-client to manage a package
  • 'name' is the name of the package; this may be an array of packages
  • action identifies which steps the chef-client will take to bring the node into the desired state
  • options, package_name, provider, source, timeout, and version 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

This resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:remove
Remove a package.

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.

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 notifiy 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 very 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: String

One (or more) additional options that are passed to the command.

package_name

Ruby Types: String, Array

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

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

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.

source

Ruby Type: String

Optional. The path to a package in the local file system.

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.

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 very 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
timeout

Ruby Types: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Types: String, Array

The version of a package to be installed or upgraded.

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Package, package
When this short name is used, the chef-client will attempt to determine the correct provider during the chef-client run.
Chef::Provider::Package::Dpkg, dpkg_package
The provider for the dpkg platform. Can be used with the options attribute.

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.

Install a package

dpkg_package 'name of package' do
  action :install
end

dsc_resource

[edit on GitHub]

Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing UNIX- and Linux-based machines. Windows PowerShell is a tool-agnostic platform that supports using Chef for configuration management.

New in Chef Client 12.6.

Desired State Configuration (DSC) is a feature of Windows PowerShell that provides a set of language extensions, cmdlets, and resources that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell.

The dsc_resource resource allows any DSC resource to be used in a Chef recipe, as well as any custom resources that have been added to your Windows PowerShell environment. Microsoft frequently adds new resources to the DSC resource collection.

Warning

Using the dsc_resource has the following requirements:

  • Windows Management Framework (WMF) 5.0 February Preview (or higher), which includes Windows PowerShell 5.0.10018.0 (or higher).

  • The RefreshMode configuration setting in the Local Configuration Manager must be set to Disabled.

    NOTE: Starting with the chef-client 12.6 release, this requirement applies only for versions of Windows PowerShell earlier than 5.0.10586.0. The latest version of Windows Management Framework (WMF) 5 has relaxed the limitation that prevented the chef-client from running in non-disabled refresh mode.

  • The dsc_script resource may not be used in the same run-list with the dsc_resource. This is because the dsc_script resource requires that RefreshMode in the Local Configuration Manager be set to Push, whereas the dsc_resource resource requires it to be set to Disabled.

    NOTE: Starting with the chef-client 12.6 release, this requirement applies only for versions of Windows PowerShell earlier than 5.0.10586.0. The latest version of Windows Management Framework (WMF) 5 has relaxed the limitation that prevented the chef-client from running in non-disabled refresh mode, which allows the Local Configuration Manager to be set to Push.

  • The dsc_resource resource can only use binary- or script-based resources. Composite DSC resources may not be used.

    This is because composite resources aren’t “real” resources from the perspective of the the Local Configuration Manager (LCM). Composite resources are used by the “configuration” keyword from the PSDesiredStateConfiguration module, and then evaluated in that context. When using DSC to create the configuration document (the Managed Object Framework (MOF) file) from the configuration command, the composite resource is evaluated. Any individual resources from that composite resource are written into the Managed Object Framework (MOF) document. As far as the Local Configuration Manager (LCM) is concerned, there is no such thing as a composite resource. Unless that changes, the dsc_resource resource and/or Invoke-DscResource command cannot directly use them.

Syntax

A dsc_resource resource block allows DSC resourcs to be used in a Chef recipe. For example, the DSC Archive resource:

Archive ExampleArchive {
  Ensure = "Present"
  Path = "C:\Users\Public\Documents\example.zip"
  Destination = "C:\Users\Public\Documents\ExtractionPath"
}

and then the same dsc_resource with Chef:

dsc_resource 'example' do
   resource :archive
   property :ensure, 'Present'
   property :path, "C:\Users\Public\Documents\example.zip"
   property :destination, "C:\Users\Public\Documents\ExtractionPath"
 end

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

dsc_resource 'name' do
  module_name                String
  notifies                   # see description
  property                   Symbol
  resource                   String
  subscribes                 # see description
end

where

  • dsc_resource is the resource
  • name is the name of the resource block
  • property is zero (or more) properties in the DSC resource, where each property is entered on a separate line, :dsc_property_name is the case-insensitive name of that property, and "property_value" is a Ruby value to be applied by the chef-client
  • module_name, property, and resource 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

This resource has the following actions:

:nothing

Default.

Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.

:reboot_action
Use to request an immediate reboot or to queue a reboot using the :reboot_now (immediate reboot) or :request_reboot (queued reboot) actions built into the reboot resource.

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.

module_name

Ruby Type: String

The name of the module from which a DSC resource originates. If this property is not specified, it will be inferred.

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 notifiy 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 very 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
property

Ruby Type: Symbol

A property from a Desired State Configuration (DSC) resource. Use this property multiple times, one for each property in the Desired State Configuration (DSC) resource. The format for this property must follow property :dsc_property_name, "property_value" for each DSC property added to the resource block.

The :dsc_property_name must be a symbol.

Use the following Ruby types to define property_value:

Ruby Windows PowerShell
Array Object[]
Chef::Util::Powershell:PSCredential PSCredential
FalseClass bool($false)
Fixnum Integer
Float Double
Hash Hashtable
TrueClass bool($true)

These are converted into the corresponding Windows PowerShell type during the chef-client run.

resource

Ruby Type: String

The name of the DSC resource. This value is case-insensitive and must be a symbol that matches the name of the DSC resource.

For built-in DSC resources, use the following values:

Value Description
:archive Use to to unpack archive (.zip) files.
:environment Use to to manage system environment variables.
:file Use to to manage files and directories.
:group Use to to manage local groups.
:log Use to to log configuration messages.
:package Use to to install and manage packages.
:registry Use to to manage registry keys and registry key values.
:script Use to to run Powershell script blocks.
:service Use to to manage services.
:user Use to to manage local user accounts.
:windowsfeature Use to to add or remove Windows features and roles.
:windowsoptionalfeature Use to configure Microsoft Windows optional features.
:windowsprocess Use to to configure Windows processes.

Any DSC resource may be used in a Chef recipe. For example, the DSC Resource Kit contains resources for configuring Active Directory components, such as xADDomain, xADDomainController, and xADUser. Assuming that these resources are available to the chef-client, the corresponding values for the resource attribute would be: :xADDomain, :xADDomainController, and xADUser.

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.

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.

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 very 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

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.

Open a Zip file

dsc_resource 'example' do
   resource :archive
   property :ensure, 'Present'
   property :path, 'C:\Users\Public\Documents\example.zip'
   property :destination, 'C:\Users\Public\Documents\ExtractionPath'
 end

Manage users and groups

dsc_resource 'demogroupadd' do
  resource :group
  property :groupname, 'demo1'
  property :ensure, 'present'
end

dsc_resource 'useradd' do
  resource :user
  property :username, 'Foobar1'
  property :fullname, 'Foobar1'
  property :password, ps_credential('P@assword!')
  property :ensure, 'present'
end

dsc_resource 'AddFoobar1ToUsers' do
  resource :Group
  property :GroupName, 'demo1'
  property :MembersToInclude, ['Foobar1']
end

Create and register a windows service

The following example creates a windows service, defines it’s execution path, and prevents windows from starting the service in case the executable is not at the defined location:

dsc_resource 'NAME' do
  resource :service
  property :name, 'NAME'
  property :startuptype, 'Disabled'
  property :path, 'D:\\Sites\\Site_name\file_to_run.exe'
  property :ensure, 'Present'
  property :state, 'Stopped'
end

Create a test message queue

The following example creates a file on a node (based on one that is located in a cookbook), unpacks the MessageQueue.zip Windows PowerShell module, and then uses the dsc_resource to ensure that Message Queuing (MSMQ) sub-features are installed, a test queue is created, and that permissions are set on the test queue:

cookbook_file 'cMessageQueue.zip' do
  path "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip"
  action :create_if_missing
end

windows_zipfile "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" do
  source "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip"
  action :unzip
end

dsc_resource 'install-sub-features' do
  resource :windowsfeature
  property :ensure, 'Present'
  property :name, 'msmq'
  property :IncludeAllSubFeature, true
end

dsc_resource 'create-test-queue' do
  resource :cPrivateMsmqQueue
  property :ensure, 'Present'
  property :name, 'Test_Queue'
end

dsc_resource 'set-permissions' do
  resource :cPrivateMsmqQueuePermissions
  property :ensure, 'Present'
  property :name, 'Test_Queue_Permissions'
  property :QueueNames, 'Test_Queue'
  property :ReadUsers, node['msmq']['read_user']
end

dsc_script

[edit on GitHub]

Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing UNIX- and Linux-based machines. Windows PowerShell is a tool-agnostic platform that supports using Chef for configuration management.

Desired State Configuration (DSC) is a feature of Windows PowerShell that provides a set of language extensions, cmdlets, and resources that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell.

Many DSC resources are comparable to built-in Chef resources. For example, both DSC and Chef have file, package, and service resources. The dsc_script resource is most useful for those DSC resources that do not have a direct comparison to a resource in Chef, such as the Archive resource, a custom DSC resource, an existing DSC script that performs an important task, and so on. Use the dsc_script resource to embed the code that defines a DSC configuration directly within a Chef recipe.

Note

Windows PowerShell 4.0 is required for using the dsc_script resource with Chef.

Note

The WinRM service must be enabled. (Use winrm quickconfig to enable the service.)

Warning

The dsc_script resource may not be used in the same run-list with the dsc_resource. This is because the dsc_script resource requires that RefreshMode in the Local Configuration Manager be set to Push, whereas the dsc_resource resource requires it to be set to Disabled.

Syntax

A dsc_script resource block embeds the code that defines a DSC configuration directly within a Chef recipe:

dsc_script 'get-dsc-resource-kit' do
  code <<-EOH
    Archive reskit
    {
      ensure = 'Present'
      path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip"
      destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules"
    }
  EOH
end

where the remote_file resource is first used to download the DSCResourceKit620082014.zip file.

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

dsc_script 'name' do
  code                       String
  command                    String
  configuration_data         String
  configuration_data_script  String
  configuration_name         String
  cwd                        String
  environment                Hash
  flags                      Hash
  imports                    Array
  notifies                   # see description
  subscribes                 # see description
  timeout                    Integer
  action                     Symbol # defaults to :run if not specified
end

where

  • dsc_script is the resource
  • name is the name of the resource block
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • code, command, configuration_data, configuration_data_script, configuration_name, cwd, environment, flags, imports, 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

This resource has the following actions:

:nothing

Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:run
Default. Use to run the DSC configuration defined as defined in this resource.

Properties

This resource has the following properties:

code

Ruby Type: String

The code for the DSC configuration script. This property may not be used in the same recipe as the command property.

command

Ruby Type: String

The path to a valid Windows PowerShell data file that contains the DSC configuration script. This data file must be capable of running independently of Chef and must generate a valid DSC configuration. This property may not be used in the same recipe as the code property.

configuration_data

Ruby Type: String

The configuration data for the DSC script. The configuration data must be a valid Windows Powershell data file. This property may not be used in the same recipe as the configuration_data_script property.

configuration_data_script

Ruby Type: String

The path to a valid Windows PowerShell data file that also contains a node called localhost. This property may not be used in the same recipe as the configuration_data property.

configuration_name

Ruby Type: String

The name of a valid Windows PowerShell cmdlet. The name may only contain letter (a-z, A-Z), number (0-9), and underscore (_) characters and should start with a letter. The name may not be null or empty. This property may not be used in the same recipe as the code property.

cwd

Ruby Type: String

The current working directory.

environment

Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags

Ruby Type: Hash

Pass parameters to the DSC script that is specified by the command property. Parameters are defined as key-value pairs, where the value of each key is the parameter to pass. This property may not be used in the same recipe as the code property. For example: flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' }). Default value: nil.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

imports

Ruby Type: Array

Warning

This property MUST be used with the code attribute.

Use to import DSC resources from a module.

To import all resources from a module, specify only the module name:

imports 'module_name'

To import specific resources, specify the module name, and then specify the name for each resource in that module to import:

imports 'module_name', 'resource_name_a', 'resource_name_b', ...

For example, to import all resources from a module named cRDPEnabled:

imports 'cRDPEnabled'

To import only the PSHOrg_cRDPEnabled resource:

imports 'cRDPEnabled', 'PSHOrg_cRDPEnabled'
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 notifiy 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 very 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
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.

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.

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 very 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
timeout

Ruby Types: Integer

The amount of time (in seconds) a command is to wait before timing out.

ps_credential Helper

Use the ps_credential helper to embed a PSCredential object—a set of security credentials, such as a user name or password—within a script, which allows that script to be run using security credentials.

For example, assuming the CertificateID is configured in the local configuration manager, the SeaPower1@3 object is created and embedded within the seapower-user script:

 dsc_script 'seapower-user' do
   code <<-EOH
     User AlbertAtom
     {
       UserName = 'AlbertAtom'
       Password = #{ps_credential('SeaPower1@3')}
     }
  EOH
  configuration_data <<-EOH
    @{
      AllNodes = @(
        @{
          NodeName = "localhost";
          CertificateID = 'A8D1234559F349F7EF19104678908F701D4167'
        }
      )
    }
  EOH
end

New in Chef client 12.5.

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.

Specify DSC code directly

DSC data can be specified directly in a recipe:

dsc_script 'emacs' do
  code <<-EOH
  Environment 'texteditor'
  {
    Name = 'EDITOR'
    Value = 'c:\\emacs\\bin\\emacs.exe'
  }
  EOH
end

Specify DSC code using a Windows Powershell data file

Use the command property to specify the path to a Windows PowerShell data file. For example, the following Windows PowerShell script defines the DefaultEditor:

Configuration 'DefaultEditor'
{
  Environment 'texteditor'
    {
      Name = 'EDITOR'
      Value = 'c:\emacs\bin\emacs.exe'
    }
}

Use the following recipe to specify the location of that data file:

dsc_script 'DefaultEditor' do
  command 'c:\dsc_scripts\emacs.ps1'
end

Pass parameters to DSC configurations

If a DSC script contains configuration data that takes parameters, those parameters may be passed using the flags property. For example, the following Windows PowerShell script takes parameters for the EditorChoice and EditorFlags settings:

$choices = @{'emacs' = 'c:\emacs\bin\emacs';'vi' = 'c:\vim\vim.exe';'powershell' = 'powershell_ise.exe'}
  Configuration 'DefaultEditor'
    {
      [CmdletBinding()]
      param
        (
          $EditorChoice,
          $EditorFlags = ''
        )
      Environment 'TextEditor'
      {
        Name = 'EDITOR'
        Value =  "$($choices[$EditorChoice]) $EditorFlags"
      }
    }

Use the following recipe to set those parameters:

dsc_script 'DefaultEditor' do
  flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' })
  command 'c:\dsc_scripts\editors.ps1'
end

Use custom configuration data

Configuration data in DSC scripts may be customized from a recipe. For example, scripts are typically customized to set the behavior for Windows PowerShell credential data types. Configuration data may be specified in one of three ways:

  • By using the configuration_data attribute
  • By using the configuration_data_script attribute
  • By specifying the path to a valid Windows PowerShell data file

The following example shows how to specify custom configuration data using the configuration_data property:

dsc_script 'BackupUser' do
  configuration_data <<-EOH
    @{
     AllNodes = @(
          @{
          NodeName = "localhost";
          PSDscAllowPlainTextPassword = $true
          })
     }
  EOH
  code <<-EOH
    $user = 'backup'
    $password = ConvertTo-SecureString -String "YourPass$(random)" -AsPlainText -Force
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $password

   User $user
     {
       UserName = $user
       Password = $cred
       Description = 'Backup operator'
       Ensure = "Present"
       Disabled = $false
       PasswordNeverExpires = $true
       PasswordChangeRequired = $false
     }
   EOH

  configuration_data <<-EOH
    @{
      AllNodes = @(
          @{
          NodeName = "localhost";
          PSDscAllowPlainTextPassword = $true
          })
      }
    EOH
end

The following example shows how to specify custom configuration data using the configuration_name property. For example, the following Windows PowerShell script defines the vi configuration:

Configuration 'emacs'
  {
    Environment 'TextEditor'
    {
      Name = 'EDITOR'
      Value = 'c:\emacs\bin\emacs.exe'
    }
}

Configuration 'vi'
{
    Environment 'TextEditor'
    {
      Name = 'EDITOR'
      Value = 'c:\vim\bin\vim.exe'
    }
}

Use the following recipe to specify that configuration:

dsc_script 'EDITOR' do
  configuration_name 'vi'
  command 'C:\dsc_scripts\editors.ps1'
end

Using DSC with other Chef resources

The dsc_script resource can be used with other resources. The following example shows how to download a file using the remote_file resource, and then uncompress it using the DSC Archive resource:

remote_file "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" do
  source 'http://gallery.technet.microsoft.com/DSC-Resource-Kit-All-c449312d/file/124481/1/DSC%20Resource%20Kit%20Wave%206%2008282014.zip'
end

dsc_script 'get-dsc-resource-kit' do
  code <<-EOH
    Archive reskit
    {
      ensure = 'Present'
      path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip"
      destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules"
    }
  EOH
end

easy_install_package

[edit on GitHub]

Use the easy_install_package resource to manage packages for the Python platform.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, the chef-client will use details that are collected by Ohai at the start of the chef-client run to determine the correct package application. Using the package resource allows a recipe to be authored in a way that allows it to be used across many platforms.

Syntax

A easy_install_package resource block manages a package on a node, typically by installing it. The simplest use of the easy_install_package resource is:

easy_install_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

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

easy_install_package 'name' do
  easy_install_binary        String
  module_name                String
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  provider                   Chef::Provider::Package::EasyInstall
  python_binary              String
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where

  • easy_install_package tells the chef-client to manage a package
  • 'name' is the name of the package
  • action identifies which steps the chef-client will take to bring the node into the desired state
  • easy_install_binary, module_name, options, package_name, provider, python_binary, source, timeout, and version 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

This resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:remove
Remove a package.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties

This resource has the following properties:

easy_install_binary

Ruby Type: String

The location of the Easy Install binary.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

module_name

Ruby Type: String

The name of the module.

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 notifiy 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 very 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: String

One (or more) additional options that are passed to the command.

package_name

Ruby Types: String, Array

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

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

python_binary

Ruby Type: String

The location of the Python binary.

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.

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.

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 very 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
source

Ruby Type: String

Optional. The path to a package in the local file system.

timeout

Ruby Types: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Types: String, Array

The version of a package to be installed or upgraded.

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Package, package
When this short name is used, the chef-client will attempt to determine the correct provider during the chef-client run.
Chef::Provider::Package::EasyInstall, easy_install_package
The provider for Python.

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.

Install a package

easy_install_package 'name of package' do
  action :install
end

env

[edit on GitHub]

Use the env resource to manage environment keys in Microsoft Windows. After an environment key is set, Microsoft Windows must be restarted before the environment key will be available to the Task Scheduler.

Note

On UNIX-based systems, the best way to manipulate environment keys is with the ENV variable in Ruby; however, this approach does not have the same permanent effect as using the env resource.

Syntax

A env resource block manages environment keys in Microsoft Windows:

env 'ComSpec' do
  value 'C:\\Windows\\system32\\cmd.exe'
end

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

env 'name' do
  delim                      String
  key_name                   String # defaults to 'name' if not specified
  notifies                   # see description
  provider                   Chef::Provider::Env
  subscribes                 # see description
  value                      String
  action                     Symbol # defaults to :create if not specified
end

where

  • env is the resource
  • name is the name of the resource block
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • delim, key_name, provider, and value 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

This resource has the following actions:

:create
Default. Create an environment variable. If an environment variable already exists (but does not match), update that environment variable to match.
:delete
Delete an environment variable.
:modify
Modify an existing environment variable. This prepends the new value to the existing value, using the delimiter specified by the delim property.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.

Properties

This resource has the following properties:

delim

Ruby Type: String

The delimiter that is used to separate multiple values for a single key.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

key_name

Ruby Type: String

The name of the key that is to be created, deleted, or modified. Default value: the name of the resource block See “Syntax” section above for more information.

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 notifiy 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 very 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
provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

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.

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.

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 very 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
value

Ruby Type: String

The value with which key_name is set.

Guards

A guard property can be used to evaluate the state of a node during the execution phase of the chef-client run. Based on the results of this evaluation, a guard property is then used to tell the chef-client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 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.
  • A block is executed as Ruby code that must return either 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 the chef-client to do nothing.

Attributes

The following properties can be used to define a guard that is evaluated during the execution phase of the chef-client run:

not_if
Prevent a resource from executing when the condition returns true.
only_if
Allow a resource to execute only if the condition returns true.

Arguments

The following arguments can be used with the not_if or only_if guard properties:

:user

Specify the user that a command will run as. For example:

not_if 'grep adam /etc/passwd', :user => 'adam'
:group

Specify the group that a command will run as. For example:

not_if 'grep adam /etc/passwd', :group => 'adam'
:environment

Specify a Hash of environment variables to be set. For example:

not_if 'grep adam /etc/passwd', :environment => {
  'HOME' => '/home/adam'
}
:cwd

Set the current working directory before running a command. For example:

not_if 'grep adam passwd', :cwd => '/etc'
:timeout

Set a timeout for a command. For example:

not_if 'sleep 10000', :timeout => 10

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.

Set an environment variable

env 'ComSpec' do
  value "C:\\Windows\\system32\\cmd.exe"
end

erl_call

[edit on GitHub]

Use the erl_call resource to connect to a node located within a distributed Erlang system. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Note

The erl_call command needs to be on the path for this resource to work properly.

Syntax

A erl_call resource block connects to a node located within a distributed Erlang system:

erl_call 'list names' do
  code 'net_adm:names().'
  distributed true
  node_name 'chef@latte'
end

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

erl_call 'name' do
  code                       String
  cookie                     String
  distributed                TrueClass, FalseClass
  name_type                  String
  node_name                  String
  notifies                   # see description
  provider                   Chef::Provider::ErlCall
  subscribes                 # see description
  action                     Symbol # defaults to :run if not specified
end

where

  • erl_call is the resource
  • name is the name of the resource block
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • code, cookie, distributed, name_type, node_name, and provider 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

This resource has the following actions:

:nothing
Prevent the Erlang call from running.
:run
Default. Run the Erlang call.

Properties

This resource has the following properties:

code

Ruby Type: String

The code to be executed on a node located within a distributed Erlang system. Default value: q().

cookie

Ruby Type: String

The magic cookie for the node to which a connection is made.

distributed

Ruby Types: TrueClass, FalseClass

The node is a distributed Erlang node. Default value: false.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

name_type

Ruby Type: String

The node_name property as a short node name (sname) or a long node name (name). A node with a long node name cannot communicate with a node with a short node name. Default value: sname.

node_name

Ruby Type: String

The hostname to which the node is to connect. Default value: chef@localhost.

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 notifiy 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 very 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
provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

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.

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.

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 very 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

Guards

A guard property can be used to evaluate the state of a node during the execution phase of the chef-client run. Based on the results of this evaluation, a guard property is then used to tell the chef-client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 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.
  • A block is executed as Ruby code that must return either 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 the chef-client to do nothing.

Attributes

The following properties can be used to define a guard that is evaluated during the execution phase of the chef-client run:

not_if
Prevent a resource from executing when the condition returns true.
only_if
Allow a resource to execute only if the condition returns true.

Arguments

The following arguments can be used with the not_if or only_if guard properties:

:user

Specify the user that a command will run as. For example:

not_if 'grep adam /etc/passwd', :user => 'adam'
:group

Specify the group that a command will run as. For example:

not_if 'grep adam /etc/passwd', :group => 'adam'
:environment

Specify a Hash of environment variables to be set. For example:

not_if 'grep adam /etc/passwd', :environment => {
  'HOME' => '/home/adam'
}
:cwd

Set the current working directory before running a command. For example:

not_if 'grep adam passwd', :cwd => '/etc'
:timeout

Set a timeout for a command. For example:

not_if 'sleep 10000', :timeout => 10

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.

Run a command

erl_call 'list names' do
  code 'net_adm:names().'
  distributed true
  node_name 'chef@latte'
end

execute

[edit on GitHub]

Use the execute resource to execute a single command. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Note

Use the script resource to execute a script using a specific interpreter (Ruby, Python, Perl, csh, or Bash).

Syntax

A execute resource block typically executes a single command that is unique to the environment in which a recipe will run. Some execute resource commands are run by themselves, but often they are run in combination with other Chef resources. For example, a single command that is run by itself:

execute 'apache_configtest' do
  command '/usr/sbin/apachectl configtest'
end

where '/usr/sbin/apachectl configtest' is a command that tests if the configuration files for Apache are valid.

Commands are often run in combination with other Chef resources. The following example shows the template resource run with the execute resource to add an entry to a LDAP Directory Interchange Format (LDIF) file:

execute 'slapadd' do
  command 'slapadd < /tmp/something.ldif'
  creates '/var/lib/slapd/uid.bdb'
  action :nothing
end

template '/tmp/something.ldif' do
  source 'something.ldif'
  notifies :run, 'execute[slapadd]', :immediately
end

where

  • '/tmp/something.ldif' specifies the location of the file
  • 'something.ldif' specifies template file from which /tmp/something.ldif is created
  • 'slapadd < /tmp/something.ldif' is the command that is run
  • /var/lib/slapd/uid.bdb prevents the execute resource block from running if that file already exists

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

execute 'name' do
  command                    String, Array # defaults to 'name' if not specified
  creates                    String
  cwd                        String
  environment                Hash # env is an alias for environment
  group                      String, Integer
  live_stream                TrueClass, FalseClass
  notifies                   # see description
  path                       Array
  provider                   Chef::Provider::Execute
  returns                    Integer, Array
  sensitive                  TrueClass, FalseClass
  subscribes                 # see description
  timeout                    Integer, Float
  umask                      String, Integer
  user                       String
  password                   String
  domain                     String
  action                     Symbol # defaults to :run if not specified
end

where

  • execute is the resource
  • name is the name of the resource block
  • command is the command to be run
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • command, creates, cwd, environment, group, live_stream, path, provider, returns, sensitive, timeout, user, password, domain and umask 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

This resource has the following actions:

:nothing
Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it.
:run
Default. Run a command.

Properties

This resource has the following properties:

command

Ruby Types: String, Array

The name of the command to be executed. Default value: the name of the resource block See “Syntax” section above for more information.

Note

Use the execute resource to run a single command. Use multiple execute resource blocks to run multiple commands.

creates

Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd

Ruby Type: String

The current working directory from which a command is run.

environment

Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

group

Ruby Types: String, Integer

The group name or group ID that must be changed before running a command.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

live_stream

Ruby Types: TrueClass, FalseClass

Send the output of the command run by this execute resource block to the chef-client event stream. Default value: false.

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 notifiy 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 very 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
path

Ruby Type: Array

An array of paths to use when searching for a command. These paths are not added to the command’s environment $PATH. The default value uses the system path.

Warning

For example:

execute 'mycommand' do
  environment 'PATH' => "/my/path/to/bin:#{ENV['PATH']}"
end
provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

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.

returns

Ruby Types: Integer, Array

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. Default value: 0.

sensitive

Ruby Types: TrueClass, FalseClass

Ensure that sensitive resource data is not logged by the chef-client. Default value: false.

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.

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 very 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
timeout

Ruby Types: Integer, Float

The amount of time (in seconds) a command is to wait before timing out. Default value: 3600.

user

Ruby Types: String

The user name of the user identity with which to launch the new process. Default value: nil. The user name may optionally be specifed with a domain, i.e. domainuser or user@my.dns.domain.com via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified.

password

Ruby Types: String

Windows only: The password of the user specified by the user property. Default value: nil. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified.

domain

Ruby Types: String

Windows only: The domain of the user user specified by the user property. Default value: nil. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property.

umask

Ruby Types: String, Integer

The file mode creation mask, or umask.

Guards

A guard property can be used to evaluate the state of a node during the execution phase of the chef-client run. Based on the results of this evaluation, a guard property is then used to tell the chef-client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 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.
  • A block is executed as Ruby code that must return either 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 the chef-client to do nothing.

Note

When using the not_if and only_if guards with the execute resource, the current working directory property (cwd) is not inherited from the resource. For example:

execute 'bundle install' do
  cwd '/myapp'
  not_if 'bundle check' # This is not run inside /myapp
end

Attributes

The following properties can be used to define a guard that is evaluated during the execution phase of the chef-client run:

not_if
Prevent a resource from executing when the condition returns true.
only_if
Allow a resource to execute only if the condition returns true.

Arguments

The following arguments can be used with the not_if or only_if guard properties:

:user

Specify the user that a command will run as. For example:

not_if 'grep adam /etc/passwd', :user => 'adam'
:group

Specify the group that a command will run as. For example:

not_if 'grep adam /etc/passwd', :group => 'adam'
:environment

Specify a Hash of environment variables to be set. For example:

not_if 'grep adam /etc/passwd', :environment => {
  'HOME' => '/home/adam'
}
:cwd

Set the current working directory before running a command. For example:

not_if 'grep adam passwd', :cwd => '/etc'
:timeout

Set a timeout for a command. For example:

not_if 'sleep 10000', :timeout => 10

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.

Run a command upon notification

execute 'slapadd' do
  command 'slapadd < /tmp/something.ldif'
  creates '/var/lib/slapd/uid.bdb'
  action :nothing
end

template '/tmp/something.ldif' do
  source 'something.ldif'
  notifies :run, 'execute[slapadd]', :immediately
end

Run a touch file only once while running a command

execute 'upgrade script' do
  command 'php upgrade-application.php && touch /var/application/.upgraded'
  creates '/var/application/.upgraded'
  action :run
end

Run a command which requires an environment variable

execute 'slapadd' do
  command 'slapadd < /tmp/something.ldif'
  creates '/var/lib/slapd/uid.bdb'
  action :run
  environment ({'HOME' => '/home/myhome'})
end

Delete a repository using yum to scrub the cache

# the following code sample thanks to gaffneyc @ https://gist.github.com/918711

execute 'clean-yum-cache' do
  command 'yum clean all'
  action :nothing
end

file '/etc/yum.repos.d/bad.repo' do
  action :delete
  notifies :run, 'execute[clean-yum-cache]', :immediately
  notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately
end

Install repositories from a file, trigger a command, and force the internal cache to reload

The following example shows how to install new Yum repositories from a file, where the installation of the repository triggers a creation of the Yum cache that forces the internal cache for the chef-client to reload:

execute 'create-yum-cache' do
 command 'yum -q makecache'
 action :nothing
end

ruby_block 'reload-internal-yum-cache' do
  block do
    Chef::Provider::Package::Yum::YumCache.instance.reload
  end
  action :nothing
end

cookbook_file '/etc/yum.repos.d/custom.repo' do
  source 'custom'
  mode '0755'
  notifies :run, 'execute[create-yum-cache]', :immediately
  notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately
end

Prevent restart and reconfigure if configuration is broken

Use the :nothing action (common to all resources) to prevent an application from restarting, and then use the subscribes notification to ask the broken configuration to be reconfigured immediately:

execute 'test-nagios-config' do
  command 'nagios3 --verify-config'
  action :nothing
  subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately
end

Notify in a specific order

To notify multiple resources, and then have these resources run in a certain order, do something like the following:

execute 'foo' do
  command '...'
  notifies :create, 'template[baz]', :immediately
  notifies :install, 'package[bar]', :immediately
  notifies :run, 'execute[final]', :immediately
end

template 'baz' do
  ...
  notifies :run, 'execute[restart_baz]', :immediately
end

package 'bar'

execute 'restart_baz'

execute 'final' do
  command '...'
end

where the sequencing will be in the same order as the resources are listed in the recipe: execute 'foo', template 'baz', execute [restart_baz], package 'bar', and execute 'final'.

Execute a command using a template

The following example shows how to set up IPv4 packet forwarding using the execute resource to run a command named forward_ipv4 that uses a template defined by the template resource:

execute 'forward_ipv4' do
  command 'echo > /proc/.../ipv4/ip_forward'
  action :nothing
end

template '/etc/file_name.conf' do
  source 'routing/file_name.conf.erb'
  notifies :run, 'execute[forward_ipv4]', :delayed
end

where the command property for the execute resource contains the command that is to be run and the source property for the template resource specifies which template to use. The notifies property for the template specifies that the execute[forward_ipv4] (which is defined by the execute resource) should be queued up and run at the end of the chef-client run.

Add a rule to an IP table

The following example shows how to add a rule named test_rule to an IP table using the execute resource to run a command using a template that is defined by the template resource:

execute 'test_rule' do
  command 'command_to_run
    --option value
    ...
    --option value
    --source #{node[:name_of_node][:ipsec][:local][:subnet]}
    -j test_rule'
  action :nothing
end

template '/etc/file_name.local' do
  source 'routing/file_name.local.erb'
  notifies :run, 'execute[test_rule]', :delayed
end

where the command property for the execute resource contains the command that is to be run and the source property for the template resource specifies which template to use. The notifies property for the template specifies that the execute[test_rule] (which is defined by the execute resource) should be queued up and run at the end of the chef-client 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

Use the platform_family? method

The following is an example of using the platform_family? method in the Recipe DSL to create a variable that can be used with other resources in the same recipe. In this example, platform_family? is being used to ensure that a specific binary is used for a specific platform before using the remote_file resource to download a file from a remote location, and then using the execute resource to install that file by running a command.

if platform_family?('rhel')
  pip_binary = '/usr/bin/pip'
else
  pip_binary = '/usr/local/bin/pip'
end

remote_file "#{Chef::Config[:file_cache_path]}/distribute_setup.py" do
  source 'http://python-distribute.org/distribute_setup.py'
  mode '0755'
  not_if { File.exist?(pip_binary) }
end

execute 'install-pip' do
  cwd Chef::Config[:file_cache_path]
  command <<-EOF
    # command for installing Python goes here
    EOF
  not_if { File.exist?(pip_binary) }
end

where a command for installing Python might look something like:

#{node['python']['binary']} distribute_setup.py
#{::File.dirname(pip_binary)}/easy_install pip

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.

Use the search recipe DSL method to find users

The following example shows how to use the search method in the Recipe DSL to search for users:

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

search("users", "*:*") do |u|
  execute "generate-openvpn-#{u['id']}" do
    command "./pkitool #{u['id']}"
    cwd '/etc/openvpn/easy-rsa'
    environment(
      'EASY_RSA' => '/etc/openvpn/easy-rsa',
      'KEY_CONFIG' => '/etc/openvpn/easy-rsa/openssl.cnf',
      'KEY_DIR' => node['openvpn']['key_dir'],
      'CA_EXPIRE' => node['openvpn']['key']['ca_expire'].to_s,
      'KEY_EXPIRE' => node['openvpn']['key']['expire'].to_s,
      'KEY_SIZE' => node['openvpn']['key']['size'].to_s,
      'KEY_COUNTRY' => node['openvpn']['key']['country'],
      'KEY_PROVINCE' => node['openvpn']['key']['province'],
      'KEY_CITY' => node['openvpn']['key']['city'],
      'KEY_ORG' => node['openvpn']['key']['org'],
      'KEY_EMAIL' => node['openvpn']['key']['email']
    )
    not_if { File.exist?("#{node['openvpn']['key_dir']}/#{u['id']}.crt") }
  end

  %w{ conf ovpn }.each do |ext|
    template "#{node['openvpn']['key_dir']}/#{u['id']}.#{ext}" do
      source 'client.conf.erb'
      variables :username => u['id']
    end
  end

  execute "create-openvpn-tar-#{u['id']}" do
    cwd node['openvpn']['key_dir']
    command <<-EOH
      tar zcf #{u['id']}.tar.gz \
      ca.crt #{u['id']}.crt #{u['id']}.key \
      #{u['id']}.conf #{u['id']}.ovpn \
    EOH
    not_if { File.exist?("#{node['openvpn']['key_dir']}/#{u['id']}.tar.gz") }
  end
end

where

  • the search will use both of the execute resources, unless the condition specified by the not_if commands are met
  • the environments property in the first execute resource is being used to define values that appear as variables in the OpenVPN configuration
  • the template resource tells the chef-client which template to use

Enable remote login for Mac OS X

execute 'enable ssh' do
  command '/usr/sbin/systemsetup -setremotelogin on'
  not_if '/usr/sbin/systemsetup -getremotelogin | /usr/bin/grep On'
  action :run
end

Execute code immediately, based on the template resource

By default, notifications are :delayed, that is they are queued up as they are triggered, and then executed at the very end of a chef-client run. To run an action immediately, use :immediately:

template '/etc/nagios3/configures-nagios.conf' do
  # other parameters
  notifies :run, 'execute[test-nagios-config]', :immediately
end

and then the chef-client would immediately run the following:

execute 'test-nagios-config' do
  command 'nagios3 --verify-config'
  action :nothing
end

Sourcing a file

The execute resource cannot be used to source a file (e.g. command 'source filename'). The following example will fail because source is not an executable:

execute 'foo' do
  command 'source /tmp/foo.sh'
end

Instead, use the script resource or one of the script-based resources (bash, csh, perl, python, or ruby). For example:

bash 'foo' do
  code 'source /tmp/foo.sh'
end

Run a Knife command

execute 'create_user' do
  command <<-EOM.gsub(/\s+/, ' ').strip!
        knife user create #{user}
      --admin
      --password password
      --disable-editing
      --file /home/vagrant/.chef/user.pem
      --config /tmp/knife-admin.rb
    EOM
end

Run install command into virtual environment

The following example shows how to install a lightweight JavaScript framework into Vagrant:

execute "install q and zombiejs" do
  cwd "/home/vagrant"
  user "vagrant"
  environment ({'HOME' => '/home/vagrant', 'USER' => 'vagrant'})
  command "npm install -g q zombie should mocha coffee-script"
  action :run
end

Run a command as a named user

The following example shows how to run bundle install from a chef-client run as a specific user. This will put the gem into the path of the user (vagrant) instead of the root user (under which the chef-client runs):

execute '/opt/chefdk/embedded/bin/bundle install' do
  cwd node['chef_workstation']['bundler_path']
  user node['chef_workstation']['user']
  environment ({
    'HOME' => "/home/#{node['chef_workstation']['user']}",
    'USER' => node['chef_workstation']['user']
  })
  not_if 'bundle check'
end

Run a command as an alternate user

Note: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator.

This right can be added and checked in a recipe using this example:

# Add 'SeAssignPrimaryTokenPrivilege' for the user
Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege')

# Check if the user has 'SeAssignPrimaryTokenPrivilege' rights
Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege')

The following example shows how to run mkdir test_dir from a chef-client run as an alternate user.

# Passing only username and password
execute 'mkdir test_dir' do
 cwd Chef::Config[:file_cache_path]
 user "username"
 password "password"
end

# Passing username and domain
execute 'mkdir test_dir' do
 cwd Chef::Config[:file_cache_path]
 domain "domain-name"
 user "user"
 password "password"
end

# Passing username = 'domain-name\\username'. No domain is passed
execute 'mkdir test_dir' do
 cwd Chef::Config[:file_cache_path]
 user "domain-name\\username"
 password "password"
end

# Passing username = 'username@domain-name'. No domain is passed
execute 'mkdir test_dir' do
 cwd Chef::Config[:file_cache_path]
 user "username@domain-name"
 password "password"
end

file

[edit on GitHub]

Use the file resource to manage files directly on a node.

Note

Use the cookbook_file resource to copy a file from a cookbook’s /files directory. Use the template resource to create a file based on a template in a cookbook’s /templates directory. And use the remote_file resource to transfer a file to a node from a remote location.

Syntax

A file resource block manages files that exist on nodes. For example, to write the home page for an Apache website:

file '/var/www/customers/public_html/index.php' do
  content '<html>This is a placeholder for the home page.</html>'
  mode '0755'
  owner 'web_admin'
  group 'web_admin'
end

where

  • '/var/www/customers/public_html/index.php' is path to the file and also the filename to be managed
  • content defines the contents of the file

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

file 'name' do
  atomic_update              TrueClass, FalseClass
  backup                     FalseClass, Integer
  checksum                   String
  content                    String
  force_unlink               TrueClass, FalseClass
  group                      String, Integer
  inherits                   TrueClass, FalseClass
  manage_symlink_source      TrueClass, FalseClass, NilClass
  mode                       String, Integer
  notifies                   # see description
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  provider                   Chef::Provider::File
  rights                     Hash
  sensitive                  TrueClass, FalseClass
  subscribes                 # see description
  verify                     String, Block
  action                     Symbol # defaults to :create if not specified
end

where

  • file is the resource
  • name is the name of the resource block; when the path property is not specified as part of a recipe, name is also the path to the file
  • content specifies the contents of the file
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • atomic_update, backup, checksum, content, force_unlink, group, inherits, manage_symlink_source, mode, owner, path, provider, rights, sensitive, and verify 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

This resource has the following actions:

:create
Default. Create a file. If a file already exists (but does not match), update that file to match.
:create_if_missing
Create a file only if the file does not exist. When the file exists, nothing happens.
:delete
Delete a file.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:touch
Touch a file. This updates the access (atime) and file modification (mtime) times for a file.

Warning

For a machine on which SELinux is enabled, the chef-client will create files that correctly match the default policy settings only when the cookbook that defines the action also conforms to the same policy.

Properties

This resource has the following properties:

atomic_update

Ruby Types: TrueClass, FalseClass

Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides file_atomic_update, which is a global setting found in the client.rb file. Default value: true.

backup

Ruby Types: FalseClass, Integer

The number of backups to be kept in /var/chef/backup (for UNIX- and Linux-based platforms) or C:/chef/backup (for the Microsoft Windows platform). Set to false to prevent backups from being kept. Default value: 5.

checksum

Ruby Types: String

The SHA-256 checksum of the file. Use to ensure that a specific file is used. If the checksum does not match, the file is not used. Default value: no checksum required.

content

Ruby Type: String

A string that is written to the file. The contents of this property replace any previous content when this property has something other than the default value. The default behavior will not modify content.

force_unlink

Ruby Types: TrueClass, FalseClass

How the chef-client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to true for the chef-client delete the non-file target and replace it with the specified file. Set to false for the chef-client to raise an error. Default value: false.

group

Ruby Types: Integer, String

A string or ID that identifies the group owner by group name, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

inherits

Ruby Types: TrueClass, FalseClass

Microsoft Windows only. Whether a file inherits rights from its parent directory. Default value: true.

manage_symlink_source

Ruby Types: TrueClass, FalseClass, NilClass

Cause the chef-client to detect and manage the source file for a symlink. Possible values: nil, true, or false. When this value is set to nil, the chef-client will manage a symlink’s source file and emit a warning. When this value is set to true, the chef-client will manage a symlink’s source file and not emit a warning. Default value: nil. The default value will be changed to false in a future version.

mode

Ruby Types: Integer, String

A quoted 3-5 character string that defines the octal mode. For example: '755', '0755', or 00755. If mode is not specified and if the file already exists, the existing mode on the file is used. If mode is not specified, the file does not exist, and the :create action is specified, the chef-client assumes a mask value of '0777' and then applies the umask for the system on which the file is to be created to the mask value. For example, if the umask on a system is '022', the chef-client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

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 notifiy 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 very 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
owner

Ruby Types: Integer, String

A string or ID that identifies the group owner by user name, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path

Ruby Type: String

The full path to the file, including the file name and its extension. For example: /files/file.txt. Default value: the name of the resource block See “Syntax” section above for more information.

Microsoft Windows: A path that begins with a forward slash (/) will point to the root of the current working directory of the chef-client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended.

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

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.

rights

Ruby Types: Integer, String

Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options.

sensitive

Ruby Types: TrueClass, FalseClass

Ensure that sensitive resource data is not logged by the chef-client. Default value: false.

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.

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 very 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
verify

Ruby Types: String, Block

A block or a string that returns true or false. A string, when true is executed as a system command.

A block is arbitrary Ruby defined within the resource block by using the verify property. When a block is true, the chef-client will continue to update the file as appropriate.

For example, this should return true:

file '/tmp/baz' do
  verify { 1 == 1 }
end

This should return true:

file '/etc/nginx.conf' do
  verify 'nginx -t -c %{path}'
end

Warning

For releases of the chef-client prior to 12.5 (chef-client 12.4 and earlier) the correct syntax is:

file '/etc/nginx.conf' do
  verify 'nginx -t -c %{file}'
end

See GitHub issues https://github.com/chef/chef/issues/3232 and https://github.com/chef/chef/pull/3693 for more information about these differences.

This should return true:

file '/tmp/bar' do
  verify { 1 == 1}
end

And this should return true:

file '/tmp/foo' do
  verify do |path|
    true
  end
end

Whereas, this should return false:

file '/tmp/turtle' do
  verify '/usr/bin/false'
end

If a string or a block return false, the chef-client run will stop and an error is returned.

Atomic File Updates

Atomic updates are used with file-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out.

Atomic updates are enabled by default. They can be managed globally using the file_atomic_update setting in the client.rb file. They can be managed on a per-resource basis using the atomic_update property that is available with the cookbook_file, file, remote_file, and template resources.

Note

On certain platforms, and after a file has been moved into place, the chef-client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, the chef-client will fix up the security contexts after a file has been moved into the correct location by running the restorecon command. On the Microsoft Windows platform, the chef-client will create files so that ACL inheritance works as expected.

Windows File Security

To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes.

Access Control Lists (ACLs)

The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; the chef-client will apply them to the file or directory as required. The syntax for the rights property is as follows:

rights permission, principal, option_type => value

where

permission

Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control.

These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read.

(For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.)

principal
Use to specify a group or user name. This is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. The chef-client does not need to know if a principal is a user or a group.
option_type

A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types:

Option Type Description
:applies_to_children Specify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).
:applies_to_self Indicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.
:one_level_deep Indicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
end

or:

rights :read, ['Administrators','Everyone']
rights :full_control, 'Users', :applies_to_children => true
rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true

Some other important things to know when using the rights attribute:

  • Only inherited rights remain. All existing explicit rights on the object are removed and replaced.
  • If rights are not specified, nothing will be changed. The chef-client does not clear out the rights on a file or directory if rights are not specified.
  • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration.

Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
  deny_rights :read, ['Julian', 'Lewis']
end

or:

deny_rights :full_control, ['Sally']

Inheritance

By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The inherits property can be used to specifically tell the chef-client to apply (or not apply) inherited rights from its parent directory.

For example, the following example specifies the rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
end

and then the following example specifies how to use inheritance to deny access to the child directory:

directory 'C:\mordor\mount_doom' do
  rights :full_control, 'MORDOR\Sauron'
  inherits false # Sauron is the only person who should have any sort of access
end

If the deny_rights permission were to be used instead, something could slip through unless all users and groups were denied.

Another example also shows how to specify rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
  rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there
end

but then not use the inherits property to deny those rights on a child directory:

directory 'C:\mordor\mount_doom' do
  deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough
end

Because the inherits property is not specified, the chef-client will default it to true, which will ensure that security settings for existing files remain unchanged.

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.

Create a file

file '/tmp/something' do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

Create a file in Microsoft Windows

To create a file in Microsoft Windows, be sure to add an escape character—\—before the backslashes in the paths:

file 'C:\\tmp\\something.txt' do
  rights :read, 'Everyone'
  rights :full_control, 'DOMAIN\\User'
  action :create
end

Remove a file

file '/tmp/something' do
  action :delete
end

Set file modes

file '/tmp/something' do
  mode '0755'
end

Delete a repository using yum to scrub the cache

# the following code sample thanks to gaffneyc @ https://gist.github.com/918711

execute 'clean-yum-cache' do
  command 'yum clean all'
  action :nothing
end

file '/etc/yum.repos.d/bad.repo' do
  action :delete
  notifies :run, 'execute[clean-yum-cache]', :immediately
  notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately
end

Add the value of a data bag item to a file

The following example shows how to get the contents of a data bag item named impossible_things, create a .pem file located at some/directory/path/, and then use the content attribute to update the contents of that file with the value of the impossible_things data bag item:

private_key = data_bag_item('impossible_things', private_key_name)['private_key']

file "some/directory/path/#{private_key_name}.pem" do
  content private_key
  owner 'root'
  group 'group'
  mode '0755'
end

Write a YAML file

The following example shows how to use the content property to write a YAML file:

file "#{app['deploy_to']}/shared/config/settings.yml" do
  owner "app['owner']"
  group "app['group']"
  mode '0755'
  content app.to_yaml
end

Write a string to a file

The following example specifies a directory, and then uses the content property to add a string to the file created in that directory:

status_file = '/path/to/file/status_file'

file status_file do
  owner 'root'
  group 'root'
  mode '0755'
  content 'My favourite foremost coastal Antarctic shelf, oh Larsen B!'
end

Create a file from a copy

The following example shows how to copy a file from one directory to another, locally on a node:

file '/root/1.txt' do
  content IO.read('/tmp/1.txt')
  action :create
end

where the content attribute uses the Ruby IO.read method to get the contents of the /tmp/1.txt file.

freebsd_package

[edit on GitHub]

Use the freebsd_package resource to manage packages for the FreeBSD platform.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, the chef-client will use details that are collected by Ohai at the start of the chef-client run to determine the correct package application. Using the package resource allows a recipe to be authored in a way that allows it to be used across many platforms.

Syntax

A freebsd_package resource block manages a package on a node, typically by installing it. The simplest use of the freebsd_package resource is:

freebsd_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

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

freebsd_package 'name' do
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  provider                   Chef::Provider::Package::Freebsd
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where

  • freebsd_package tells the chef-client to manage a package
  • 'name' is the name of the package
  • action identifies which steps the chef-client will take to bring the node into the desired state
  • options, package_name, provider, source, timeout, and version 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

This resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:remove
Remove a package.

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.

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 notifiy 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 very 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: String

One (or more) additional options that are passed to the command.

package_name

Ruby Types: String, Array

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

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

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.

source

Ruby Type: String

Optional. The path to a package in the local file system.

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.

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 very 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
timeout

Ruby Types: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Types: String, Array

The version of a package to be installed or upgraded.

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" do instead of package "foo" do, script "foo" do instead of bash "foo" do, and so on—when available
  • Use the provider property 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

This resource has the following providers:

Chef::Provider::Package, package
When this short name is used, the chef-client will attempt to determine the correct provider during the chef-client run.
Chef::Provider::Package::Freebsd, freebsd_package
The provider for the FreeBSD 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.

Install a package

freebsd_package 'name of package' do
  action :install
end

gem_package

[edit on GitHub]

Warning

The chef_gem and gem_package resources are both used to install Ruby gems. For any machine on which the chef-client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to the chef-client. Use the chef_gem resource to install gems into the instance of Ruby that is dedicated to the chef-client. Use the gem_package resource to install all other gems (i.e. install gems system-wide).

Use the gem_package resource to manage gem packages that are only included in recipes. When a package is installed from a local file, it must be added to the node using the remote_file or cookbook_file resources.

Note

The gem_package resource must be specified as gem_package and cannot be shortened to package in a recipe.

Syntax

A gem_package resource block manages a package on a node, typically by installing it. The simplest use of the gem_package resource is:

gem_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

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

gem_package 'name' do
  clear_sources              TrueClass, FalseClass
  gem_binary                 String
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  provider                   Chef::Provider::Package::Rubygems
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where

  • gem_package tells the chef-client to manage a package
  • 'name' is the name of the package
  • action identifies which steps the chef-client will take to bring the node into the desired state
  • clear_sources, gem_binary, options, package_name, provider, source, timeout, and version 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.

Gem Package Options

The RubyGems package provider attempts to use the RubyGems API to install gems without spawning a new process, whenever possible. A gems command to install will be spawned under the following conditions:

  • When a gem_binary property is specified (as a hash, a string, or by a .gemrc file), the chef-client will run that command to examine its environment settings and then again to install the gem.
  • When install options are specified as a string, the chef-client will span a gems command with those options when installing the gem.
  • The omnibus installer will search the PATH for a gem command rather than defaulting to the current gem environment. As part of enforce_path_sanity, the bin directories area added to the PATH, which means when there are no other proceeding RubyGems, the installation will still be operated against it.

Specify with Hash

If an explicit gem_binary parameter is not being used with the gem_package resource, it is preferable to provide the install options as a hash. This approach allows the provider to install the gem without needing to spawn an external gem process.

The following RubyGems options are available for inclusion within a hash and are passed to the RubyGems DependencyInstaller:

  • :env_shebang
  • :force
  • :format_executable
  • :ignore_dependencies
  • :prerelease
  • :security_policy
  • :wrappers

For more information about these options, see the RubyGems documentation: http://rubygems.rubyforge.org/rubygems-update/Gem/DependencyInstaller.html.

Example

gem_package 'bundler' do
  options(:prerelease => true, :format_executable => false)
end

Specify with String

When using an explicit gem_binary, options must be passed as a string. When not using an explicit gem_binary, the chef-client is forced to spawn a gems process to install the gems (which uses more system resources) when options are passed as a string. String options are passed verbatim to the gems command and should be specified just as if they were passed on a command line. For example, --prerelease for a pre-release gem.

Example

gem_package 'nokogiri' do
  gem_binary('/opt/ree/bin/gem')
  options('--prerelease --no-format-executable')
end

Specify with .gemrc File

Options can be specified in a .gemrc file. By default the gem_package resource will use the Ruby interface to install gems which will ignore the .gemrc file. The gem_package resource can be forced to use the gems command instead (and to read the .gemrc file) by adding the gem_binary attribute to a code block.

Example

A template named gemrc.erb is located in a cookbook’s /templates directory:

:sources:
- http://<%= node['gem_file']['host'] %>:<%= node['gem_file']['port'] %>/

A recipe can be built that does the following:

  • Builds a .gemrc file based on a gemrc.erb template
  • Runs a Gem.configuration command
  • Installs a package using the .gemrc file
template '/root/.gemrc' do
  source 'gemrc.erb'
  action :create
  notifies :run, 'ruby_block[refresh_gemrc]', :immediately
end

ruby_block 'refresh_gemrc' do
  action :nothing
  block do
    Gem.configuration = Gem::ConfigFile.new []
  end
end

gem_package 'di-ruby-lvm' do
  gem_binary '/opt/chef/embedded/bin/gem'
  action :install
end

Actions

This resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the chef-client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:reconfig
Reconfigure a package. This action requires a response file.
:remove
Remove a package.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties

This resource has the following properties:

clear_sources

Ruby Types: TrueClass, FalseClass

Set to true to download a gem from the path specified by the source property (and not from RubyGems). Default value: false.

gem_binary

Ruby Type: String

A property for the gem_package provider that is used to specify a gems binary. By default, the same version of Ruby that is used by the chef-client will be installed.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

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 notifiy 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 very 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: String

One (or more) additional options that are passed to the command.

package_name

Ruby Types: String, Array

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

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

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.

source

Ruby Type: String

Optional. The URL at which the gem package is located.

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.

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 very 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