Resources Reference

[edit on GitHub]

This reference describes each of the resources available to the Chef Client, including a list of actions, properties, and usage examples.

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
end

Properties

The following properties are common to every resource:

ignore_failure

Ruby Type: true, false | Default Value: false

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by the chef-client.

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 retries common property

service 'apache' do
  action [ :enable, :start ]
  retries 3
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

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 interpreter 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 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 notify 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
  notifies :restart, 'service[nginx]', :immediately
end

Restart one service before restarting another

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

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

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

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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 the test from starting automatically, and then use the subscribes notification to run a configuration test when a change to the template is detected:

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 that is based on a template, use the template and service resources together in the same recipe, similar to the following:

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

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

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

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 macOS 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 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 into the Chef Client:

apt_package resource

[edit on GitHub]

Use the apt_package resource to manage packages on 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, Array
  overwrite_config_files     true, false # default value: 'false'
  package_name               String, Array # defaults to 'name' if not specified
  response_file              String
  response_file_variables    Hash
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • apt_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • default_release, options, package_name, 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

The apt_package 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.
: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.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties

The apt_package resource has the following properties:

default_release

Ruby Type: String

The default release. For example: stable.

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String, Array

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.

overwrite_config_files

Ruby Type: true, false | Default Value: false

Overwrite existing configuration files with those supplied by the package, if prompted by APT.

New in Chef Client 14.0.

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: 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, DNF, 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 %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(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.

Examples

The following examples demonstrate various approaches for using apt_update in recipes.

Install a package using package manager

apt_package 'name of package' do
  action :install
end

Install without using recommend packages as a dependency

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

apt_preference resource

[edit on GitHub]

The apt_preference resource allows for the creation of APT preference files. Preference files are used to control which package versions and sources are prioritized during installation.

New in Chef Client 13.3.

Syntax

The apt_preference resource has the following syntax:

apt_preference 'name' do
  glob              String
  package_name      String # default value: 'name' unless specified
  pin               String
  pin_priority      String, Integer
  action            Symbol # defaults to :add if not specified
end

where:

  • apt_preference is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • glob, package_name, pin, and pin_priority are the properties available to this resource.

Actions

The apt_preference resource has the following actions:

add
Default action. Creates a preferences file under /etc/apt/preferences.d.
remove
Removes the preferences file, thus unpinning the package.

Properties

The apt_preference resource has the following properties:

glob

Ruby Type: String

Pin by glob() expression or with regular expressions surrounded by /.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The name of the package. Default value: name.

pin

Ruby Type: String

The package version or repository to pin.

pin_priority

Ruby Type: String, Integer

Sets the Pin-Priority for a package. See the APT pinning documentation for more details.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Examples

Pin a package to a specific version

This example pins the libmysqlclient16 package to version 5.1.49-3:

apt_preference 'libmysqlclient16' do
  pin          'version 5.1.49-3'
  pin_priority '700'
end

Note that the pin_priority of 700 ensures that this version will be preferred over any other available versions.

Unpin a package

This example unpins the libmysqlclient16 package, disabling all preferences for it:

apt_preference 'libmysqlclient16' do
  action :remove
end

Pin all packages to prefer a specific repository

This example instructs APT to prefer the packages.dotdeb.org repository:

apt_preference 'dotdeb' do
  glob         '*'
  pin          'origin packages.dotdeb.org'
  pin_priority '700'
end

apt_repository resource

[edit on GitHub]

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

Syntax

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

apt_repository 'nginx' do
  uri        'http://nginx.org/packages/ubuntu/'
  components ['nginx']
end

where

  • apt_repository is the resource
  • name is the name of the APT repository, or the name of the resource block. Must not contain spaces.
  • 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               true, false
   deb_src               true, false
   keyserver             String
   key                   String, Array
   key_proxy             String
   cookbook              String
   cache_rebuild         true, false
   sensitive             true, false
   action                Symbol # defaults to :add if not specified
end

where:

  • apt_repository is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • 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:

arch

Ruby Type: String, false

Constrain packages to a particular CPU architecture such as i386 or amd64.

cache_rebuild

Ruby Type: true, false | Default Value: true

Determines whether to rebuild the APT package cache.

components

Ruby Type: Array | Default Value: lazy default

Package groupings, such as ‘main’ and ‘stable’.

cookbook

Ruby Type: String, false

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.

deb_src

Ruby Type: true, false | Default Value: false

Determines whether or not to add the repository as a source repo as well.

distribution

Ruby Type: String, false | Default Value: lazy default

Usually a distribution’s codename, such as trusty, xenial or bionic. Default value: the codename of the node’s distro.

key

Ruby Type: String, Array, false | Default Value: lazy default

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

key_proxy

Ruby Type: String, false

If set, a specified proxy is passed to GPG via http-proxy=.

keyserver

Ruby Type: String, false | Default Value: keyserver.ubuntu.com

The GPG keyserver where the key for the repo should be retrieved.

repo_name

Ruby Type: String

The name of the repository to configure, if it differs from the name of the resource block. The value of this setting must not contain spaces.

sensitive

Ruby Type: true, false | Default Value: false

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

trusted

Ruby Type: true, false | Default Value: false

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

uri

Ruby Type: String

The base of the Debian distribution.

Examples

Add repository with basic settings

apt_repository 'nginx' do
  uri        'http://nginx.org/packages/ubuntu/'
  components ['nginx']
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'
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 repository that requires multiple keys to authenticate packages

apt_repository 'rundeck' do
  uri 'https://dl.bintray.com/rundeck/rundeck-deb'
  distribution '/'
  key ['379CE192D401AB61', 'http://rundeck.org/keys/BUILD-GPG-KEY-Rundeck.org.key']
  keyserver 'keyserver.ubuntu.com'
  action :add
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 resource

[edit on GitHub]

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

Syntax

An apt_update resource block defines the update frequency for APT repositories:

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

where:

  • apt_update is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • frequency is the property available to this resource.

Nameless

This resource can be nameless. Add the resource itself to your recipe to get the default behavior:

apt_update

will behave the same as:

apt_update 'update'

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 | Default Value: 86400

Determines how frequently (in seconds) APT repository updates are made. Use this property when the :periodic action is specified.

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

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 'update'

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
  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, 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 Type: String, Integer

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

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
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
retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

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.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Integer, Float | Default Value: 3600

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

user

Ruby Type: String, Integer

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

umask

Ruby Type: 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

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 resource

[edit on GitHub]

Use the batch resource to execute a batch script using the cmd.exe interpreter on Windows. The batch resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. 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.

Changed in 12.19 to support windows alternate user identity in execute resources.

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
  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, 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 Type: 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 Type: 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 Type: true, false | Default Value: false

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

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

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

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.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Integer, Float | Default Value: 3600

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

user

Ruby Type: String

The user name of the user identity with which to launch the new process. 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 Type: String

Windows only: The password of the user specified by the user property. 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 Type: String

Windows only: The domain of the user user specified by the user property. 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 https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/cmd 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 resource

[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 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
  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, 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 Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String, Array

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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 resource

[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.

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 config.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 config.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-shell -z named_configuration

where:

  • named_configuration is an existing configuration file in ~/.chef/named_configuration/chef_shell.rb, such as production, staging, or test

Once in chef-shell, commands can be run against objects as follows:

$ chef (preprod) > items.command
  • 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 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/username/.rvm/ree-1.8.7-2009.10/lib/ruby/1.8/tracer.rb:150: warning: tried to create Proc object without a block
  /Users/username/.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/username/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.

build_essential resource

[edit on GitHub]

Use the build_essential resource to install the packages required for compiling C software from source.

New in Chef Client 14.0.

Syntax

The build_essential resource has the following syntax:

build_essential 'name' do
  compile_time      true, false # default value: false
  action            Symbol # defaults to :install if not specified
end

where:

  • build_essential is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • compile_time is the property available to this resource.

Actions

The build_essential resource has the following actions:

:install
Default. Install the build essential packages.
: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

compile_time

Ruby Type: true, false | Default Value: false

Install the build essential packages at compile time.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

cab_package resource

[edit on GitHub]

Use the cab_package resource to install or remove Microsoft Windows cabinet (.cab) packages.

Syntax

A cab_package resource installs or removes a cabinet package from the specified file path.

cab_package 'name' do
  source String
end

where:

  • cab_package is the resource
  • name is the name of the resource block
  • source is the local path or URL for the cabinet package

Actions

This resource has the following actions:

:install
Installs the cabinet package.
:remove
Removes the cabinet package.

Properties

This resource has the following properties:

source

Ruby Type: String

The local file path or URL for the CAB package.

Examples

Using local path in source

cab_package 'Install .NET 3.5 sp1 via KB958488' do
  source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab'
  action :install
end
cab_package 'Remove .NET 3.5 sp1 via KB958488' do
  source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab'
  action :remove
end

Using URL in source

cab_package 'Install .NET 3.5 sp1 via KB958488' do
  source 'https://s3.amazonaws.com/my_bucket/Windows6.1-KB958488-x64.cab'
  action :install
end
cab_package 'Remove .NET 3.5 sp1 via KB958488' do
  source 'https://s3.amazonaws.com/my_bucket/Temp\Windows6.1-KB958488-x64.cab'
  action :remove
end

chef_gem resource

[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              true, false
  compile_time               true, false
  gem_binary                 String
  include_default_source     true, false
  notifies                   # see description
  options                    String
  package_name               String # defaults to 'name' if not specified
  source                     String, Array
  subscribes                 # see description
  timeout                    String, Integer
  version                    String
  action                     Symbol # defaults to :install if not specified
end

where:

  • chef_gem is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • clear_sources, include_default_source, gem_binary, options, package_name, 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

The chef_gem resource has the following properties:

clear_sources

Ruby Type: true, false | Default Value: false

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

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 Type: true, false | Default Value: false

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.

gem_binary

Ruby Type: String

The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by the chef-client will be installed.

include_default_source

Ruby Type: true, false | Default Value: true

Set to false to not include Chef::Config[:rubygems_url] in the sources.

New in Chef Client 13.0.

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String, Hash, Array,

Options for the gem install, either a Hash or a String. When a hash is given, the options are passed to Gem::DependencyInstaller.new, and the gem will be installed via the gems API. When a String is given, the gem will be installed by shelling out to the gem command. Using a Hash of options with an explicit gem_binary will result in undefined behavior.

package_name

Ruby Type: String

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source

Ruby Type: String, Array

Optional. The URL, or list of URLs, at which the gem package is located. This list is added to the source configured in Chef::Config[:rubygems_url] (see also include_default_source) to construct the complete list of rubygems sources. Users in an ‘airgapped’ environment should set Chef::Config[:rubygems_url] to their local RubyGems mirror.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String

The version of a gem to be installed or upgraded.

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

apt_update

node.override['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 resource

[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.

New in Chef Client 14.0.

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.normal['chef_client']['load_gems']['chef-reporting'] = {
  :require_name => 'chef_reporting',
  :action => :install
}

node.normal['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 given to the resource block.
  • action identifies which 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

The chef_handler 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

The chef_handler resource has the following properties:

arguments

Ruby Type: Array, Hash | Default Value: []

An array of arguments that are passed to the initializer for the handler class. 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 Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

supports

Warning

This property has been deprecated, and will be removed in the future. Use the type property instead.

Ruby Type: Hash | Default Value: { report: true, exception: true }.

The type of handler. Possible values: :exception, :report, or :start.

type

Ruby Type: Hash | Default Value: { report: true, exception: true }.

The type of handler. Possible values: :exception, :report, or :start.

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):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_config resource

[edit on GitHub]

Use the chocolatey_config resource to add or remove Chocolatey configuration keys.

New in Chef Client 14.3.

Syntax

The chocolatey_config resource has the following syntax:

chocolatey_config 'name' do
  config_key      String # default value: 'name' unless specified
  value           String
  action          Symbol # defaults to :set if not specified
end

where:

  • chocolatey_config is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • config_key and value are the properties available to this resource.

Actions

The chocolatey_config resource has the following actions:

:set
Default. Sets a Chocolatey config value.
:unset
Unsets a Chocolatey config value.
: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

The chocolatey_config resource has the following properties:

config_key

Ruby Type: String | Default Value: 'name'

The name of the config. The resource’s name will be used if this isn’t provided.

value

Ruby Type: String

The value to set.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

chocolatey_package resource

[edit on GitHub]

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

Warning

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

New in Chef Client 12.7.

Syntax

A chocolatey_package resource manages packages using Chocolatey on 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
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  returns                    Integer, Array # default value: [0]
  source                     String
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • chocolatey_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • options, package_name, 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.

Deprecated as of Chef 13.7

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

Properties

The chocolatey_package resource has the following properties:

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source

Ruby Type: String

Optional. The path to a package in the local file system or a reachable UNC path. Ensure that the path specified is to the folder containing the chocolatey package(s), not to the package itself.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

returns

Ruby Type: Integer, Array of Integers

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

The syntax for returns is:

returns [0, 1605, 1614, 1641]

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

Install a package with options

This example uses Chocolatey’s --checksum option:

chocolatey_package 'name of package' do
  options '--checksum 1234567890'
  action :install
end

chocolatey_source resource

[edit on GitHub]

Use the chocolatey_source resource to add or remove Chocolatey sources.

New in Chef Client 14.3.

Syntax

The chocolatey_source resource has the following syntax:

chocolatey_source 'name' do
  bypass_proxy      true, false # default value: false
  priority          Integer # default value: 0
  source            String
  source_name       String # default value: 'name' unless specified
  action            Symbol # defaults to :add if not specified
end

where:

  • chocolatey_source is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • bypass_proxy, priority, source, and source_name are the properties available to this resource.

Actions

The chocolatey_source resource has the following actions:

:add
Default. Adds a Chocolatey source.
:remove
Removes a Chocolatey source.
: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

The chocolatey_source resource has the following properties:

bypass_proxy

Ruby Type: true, false | Default Value: false

Whether or not to bypass the system’s proxy settings to access the source.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

The priority level of the source.

source

Ruby Type: String

The source URL.

source_name

Ruby Type: String | Default Value: 'name'

The name of the source to add. The resource’s name will be used if this isn’t provided.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

cookbook_file resource

[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              true, false
  backup                     false, Integer
  cookbook                   String
  force_unlink               true, false
  group                      String, Integer
  inherits                   true, false
  manage_symlink_source      true, false
  mode                       String, Integer
  notifies                   # see description
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  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 given to the resource block.
  • action identifies which 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, 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

The cookbook_file 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

The cookbook_file resource has the following properties:

atomic_update

Ruby Type: true, false

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.

backup

Ruby Type: Integer, false | Default Value: 5

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.

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 Type: true, false | Default Value: false

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.

group

Ruby Type: 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 Type: true, false | Default Value: false

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

inherits

Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

manage_symlink_source

Ruby Type: true, false | Default Value: true (with warning)

Change the behavior of the file resource if it is pointed at a symlink. When this value is set to true, the Chef client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to false, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file.

The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning.

mode

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

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

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

The syntax for notifies is:

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

Ruby Type: 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.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

rights

Ruby Type: 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 Type: String, Array | Default Value: 'name'

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. This can be used to distribute specific files depending upon the platform used - see File Specificity 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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: 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.

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-16.04
   ubuntu-16
   ubuntu
   redhat-5.11
   redhat-6.9
   ...
   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 16.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-16.04/apache2_module_conf_generate.pl
ubuntu-16/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 package resources in the same recipe

When a cookbook_file resource and a 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

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 resource

[edit on GitHub]

Use the cron resource to manage cron entries for time-based job scheduling.

Warning

The cron resource should only be used to modify an entry in a crontab file. The cron_d resource directly manages cron.d files. This resource ships in Chef 14.4 or later and can also be found in the cron cookbook) for previous chef-client releases.

Syntax

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

cron 'cookbooks_report' do
  action :create
  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
  environment      Hash
  home             String
  hour
  mailto           String
  minute
  month
  path             String
  shell            String
  time             Symbol
  user             String # default value: root
  weekday
  action           Symbol # defaults to :create if not specified
end

where:

  • cron is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • command, day, environment, home, hour, mailto, minute, month, path, shell, time, user, and weekday are the properties available to this resource.

Actions

The cron 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.

Note

Chef can only reliably manage crontab entries that it creates. To remove existing system entries we may use execute resource with a guard like:

execute "remove foo_daemon from crontab" do
  command "sed -i '/foo_daemon/d' /etc/crontab"
  only_if "grep 'foo_daemon' /etc/crontab 2>&1 >/dev/null"
end

Properties

The cron 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 | Default Value: *

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

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 | Default Value: *

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

ignore_failure

Ruby Type: true, false | Default Value: false

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

mailto

Ruby Type: String

Set the MAILTO environment variable.

minute

Ruby Type: String | Default Value: *

The minute at which the cron entry should run (0 - 59).

month

Ruby Type: String | Default Value: *

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

Set the PATH environment variable.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Symbol

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

user

Ruby Type: String | Default Value: root

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.

weekday

Ruby Type: String | Default Value: *

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

Examples

The following examples demonstrate various approaches for using resources in recipes:

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

cron_d resource

[edit on GitHub]

Use the cron_d resource to manage cron job files in the /etc/cron.d directory.

Warning

Chef also ships the cron resource for managing the monolithic /etc/crontab file on platforms that lack cron.d support. See the cron resource for information on using that resource.

New in Chef Client 14.4.

Syntax

A cron_d resource block manages cron.d files. For example, to get a weekly cookbook report from the Chef Supermarket:

cron_d 'cookbooks_report' do
  action :create
  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_d resource is:

cron_d 'name' do
  command               String
  comment               String
  cookbook              String
  cron_name             String # default value: 'name' unless specified
  day                   Integer, String # default value: *
  environment           Hash
  home                  String
  hour                  Integer, String # default value: *
  mailto                String
  minute                Integer, String # default value: *
  mode                  String, Integer # default value: 0600
  month                 Integer, String # default value: *
  path                  String
  predefined_value      String
  random_delay          Integer
  shell                 String
  user                  String # default value: root
  weekday               Integer, String # default value: *
  action                Symbol # defaults to :create if not specified
end

where:

  • cron_d is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • command, comment, cookbook, cron_name, day, environment, home, hour, mailto, minute, mode, month, path, predefined_value, random_delay, shell, user, and weekday are the properties available to this resource.

Actions

The cron_d resource has the following actions:

:create
Default. “Add a cron definition file to /etc/cron.d, but do not update an existing file.
:delete
Remove a cron definition file from /etc/cron.d if it exists.
:create_if_missing
Add a cron definition file to /etc/cron.d, but do not update an existing 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.

Properties

The cron_d resource has the following properties:

command

Ruby Type: String | REQUIRED

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"
comment

Ruby Type: String

A comment to place in the cron.d file.

cookbook
Ruby Type: String
cron_name

Ruby Type: String | Default Value: 'name'

Set the name of the cron job. If this isn’t specified we’ll use the resource name.

day

Ruby Type: Integer, String | Default Value: *

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

environment

Ruby Type: Hash

A Hash containing additional arbitrary environment variables under which the cron job will be run 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 in the cron.d file.”

hour

Ruby Type: Integer, String | Default Value: *

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

ignore_failure

Ruby Type: true, false | Default Value: false

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

mailto

Ruby Type: String

Set the MAILTO environment variable in the cron.d file.

minute

Ruby Type: Integer, String | Default Value: *

The minute at which the cron entry should run (0 - 59).

mode
Ruby Type: String, Integer | Default Value: 0600
month

Ruby Type: Integer, String | Default Value: *

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

Set the PATH environment variable in the cron.d file.

predefined_value

Ruby Type: String

Schedule your cron job with one of the special predefined value instead of ** * pattern. This correspond to “@reboot”, “@yearly”, “@annually”, “@monthly”, “@weekly”, “@daily”, “@midnight” or “@hourly”.

random_delay

Ruby Type: Integer

Set the RANDOM_DELAY environment variable in the cron.d file.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

shell

Ruby Type: String

Set the SHELL environment variable in the cron.d file.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String | Default Value: root

The name of the user that runs the command.

weekday

Ruby Type: Integer, String | Default Value: *

The day of the week on which this entry is to run (0-7, mon-sun, or *), where Sunday is both 0 and 7.

Examples

The following examples demonstrate various approaches for using resources in recipes

Run a program at a specified interval

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

Run an entry if a folder exists

cron_d '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 { ::File.exist?('/home/jboss') }
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_d '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_d 'name_of_cron_entry' do
  minute '0'
  hour '20'
  day '*'
  month '11'
  weekday '1-5'
  action :create
end

cron_access resource

[edit on GitHub]

Use the cron_access resource to manage the /etc/cron.allow and /etc/cron.deny files. Note: This resource previously shipped in the cron cookbook as cron_manage, which it can still be used as for backwards compatibility with existing chef-client releases.

New in Chef Client 14.4.

Syntax

The cron_access resource has the following syntax:

cron_access 'name' do
  user      String # default value: 'name' unless specified
  action    Symbol # defaults to :allow if not specified
end

where:

  • cron_access is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • user is the property available to this resource.

Actions

The cron_access resource has the following actions:

:allow
Default. Add the user to the cron.allow file.
:deny
Add the user to the cron.deny 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.

Properties

The cron_access resource has the following properties:

user

Ruby Type: String | Default Value: 'name'

The user to allow or deny. If not provided we’ll use the resource name.

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Examples

The following examples demonstrate various approaches for using resources in recipes:

Add the mike user to cron.allow

cron_access 'mike'

Add the mike user to cron.deny

cron_access 'mike' do
  action :deny
end

Specify the username with the user property

cron_access 'Deny the tomcat access to cron for security purposes' do
  user 'jenkins'
  action :deny
end

csh resource

[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
  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 given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • code, creates, cwd, environment, flags, group, path, 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

The csh 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

The csh resource has the following properties:

code

Ruby Type: String | REQUIRED

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

Set the current working directory before running a command.

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 Type: String, Integer

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

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
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
retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

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.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Integer, Float | Default Value: 3600

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

user

Ruby Type: String, Integer

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

umask

Ruby Type: 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

Examples

None.

directory resource

[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                   true, false
  mode                       String, Integer
  notifies                   # see description
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  recursive                  true, false
  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, 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

The directory 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 Type: 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 Type: true, false | Default Value: false

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

inherits

Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

mode

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

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

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

The syntax for notifies is:

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

Ruby Type: 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 | Default Value: 'name'

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.

recursive

Ruby Type: true, false | Default Value: false

Create or delete parent directories recursively. For the owner, group, and mode properties, the value of this attribute applies only to the leaf directory.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

rights

Ruby Type: 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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

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

dmg_package resource

[edit on GitHub]

Use the dmg_package resource to install a package from a .dmg file. The resource will retrieve the file from a remote URL, mount it using OS X’s hdidutil, copy the application to the specified destination (/Applications), and detach the image using hdiutil. The .dmg file will be stored in the Chef::Config[:file_cache_path].

New in Chef Client 14.0.

Syntax

This resource has the following syntax:

dmg_package 'name' do
  accept_eula                true, false # default value: 'false'
  allow_untrusted            true, false # default value: 'false'
  app                        String # default value: 'name'
  checksum                   String
  destination                String # default value: '/Applications'
  dmg_name                   String
  dmg_passphrase             String
  file                       String
  headers                    Hash, nil # default value: 'nil'
  notifies                   # see description
  owner                      String
  package_id                 String
  source                     String
  subscribes                 # see description
  type                       String # default value: 'app'
  volumes_dir                String
  action                     Symbol # defaults to :install if not specified
end

where:

  • dmg_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • accept_eula, allow_untrusted, app, checksum, destination, dmg_name, dmg_passphrase, file, headers, notifies, owner, package_id, source, subscribes, type, and volumes_dir are the properties available to this resource

Actions

The dmg_package resource has the following actions:

:install
Default. Installs the application.
: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

The dmg_package resource has the following properties:

accept_eula

Ruby Type: true, false | Default Value: false

Specify if the application’s EULA should be accepted, if applicable.

allow_untrusted

Ruby Type: true, false | Default Value: false

Allow installation of packages that do not have trusted certificates.

app

Ruby Type: String | Default Value: 'name'

The name of the application as it appears in the /Volumes directory, if it differs from the resource block name.

checksum

Ruby Type: String

The sha256 checksum of the .dmg file to download.

destination

Ruby Type: String | Default Value: /Applications

The directory to copy the .app into.

dmg_name

Ruby Type: String

The name of the .dmg file if it differs from that of the app, or if the name has spaces.

dmg_passphrase

Ruby Type: String

Specify a passphrase to be used to decrypt the .dmg file during the mount process.

file

Ruby Type: String

The full path to the .dmg file on the local system.

headers

Ruby Type: Hash, nil | Default Value: nil

Allows custom HTTP headers (like cookies) to be set on the remote_file resource.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The system user that should own the package installation.

package_id

Ruby Type: String

The package ID that is registered with pkgutil when a pkg or mpkg is installed.

source

Ruby Type: String

The remote URL that is used to download the .dmg file, if specified.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String | Default Value: app

The type of package.

volumes_dir

Ruby Type: String

The directory under /Volumes where the dmg is mounted, if it differs from the name of the .dmg file.

dnf_package resource

[edit on GitHub]

Use the dnf_package resource to install, upgrade, and remove packages with DNF for Fedora platforms. The dnf_package resource is able to resolve provides data for packages much like DNF can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides, and library names.

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 dnf_package resource block manages a package on a node, typically by installing it. The simplest use of the dnf_package resource is:

dnf_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 dnf_package resource is:

dnf_package 'name' do
  arch                       String, Array
  flush_cache                Array
  ignore_failure             true, false # defaults to ``false``
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  retries                    Integer
  retry_delay                Integer
  sensitive                  true, false # defaults to ``false``
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • dnf_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • arch, flush_cache, etc. are the properties available to this resource. See the Properties section below for more information about all of the properties that may be used with this resource.

Actions

The dnf_package 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 DNF package to a specific version.
: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.
:unlock
Unlocks the DNF package so that it can be upgraded to a newer version.
:upgrade
Install a package and/or ensure that a package is the latest version. This action will ignore the version attribute.

Properties

The dnf_package resource has the following properties:

arch

Ruby Type: String, Array

The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name.

flush_cache

Ruby Type: Array

Flush the in-memory cache before or after a DNF operation that installs, upgrades, or removes a package. Default value: [ :before, :after ]. The value may also be a Hash: ( { :before => true/false, :after => true/false } ).

DNF automatically synchronizes remote metadata to a local cache. The chef-client creates a copy of the local cache, and then stores it in-memory during the chef-client run. The in-memory cache allows packages to be installed during the chef-client run without the need to continue synchronizing the remote metadata to the local cache while the chef-client run is in-progress.

As an array:

dnf_package 'some-package' do
  #...
  flush_cache [ :before ]
  #...
end

and as a Hash:

dnf_package 'some-package' do
  #...
  flush_cache( { :after => true } )
  #...
end

Note

The flush_cache property does not flush the local DNF cache! Use dnf tools—dnf clean metadata, dnf clean packages, dnf clean all—to clean the local DNF cache.

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String, Array

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

package_name

Ruby Type: String, Array

One of the following: the name of a package, the name of a package and its architecture, the name of a dependency. Default value: the name of the resource block. See “Syntax” section above for more information.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type true, false | Default Value: false

Ensure that sensitive resource data is not logged by the chef-client.
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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded. This property is ignored when using the :upgrade action.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Yum, DNF, 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 %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(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.

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 an exact version

dnf_package 'netpbm = 10.35.58-8.el5'

Install a minimum version

dnf_package 'netpbm >= 10.35.58-8.el5'

Install a minimum version using the default action

dnf_package 'netpbm'

To install a package

dnf_package 'netpbm' do
  action :install
end

To install a partial minimum version

dnf_package 'netpbm >= 10'

To install a specific architecture

dnf_package 'netpbm' do
  arch 'i386'
end

or:

dnf_package 'netpbm.x86_64'

To install a specific version-release

dnf_package 'netpbm' do
  version '10.35.58-8.el5'
end

To install a specific version (even when older than the current)

dnf_package 'tzdata' do
  version '2011b-1.el5'
end

Handle cookbook_file and dnf_package resources in the same recipe

When a cookbook_file resource and a dnf_package resource are both called from within the same recipe, use the flush_cache attribute to dump the in-memory DNF 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

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

dpkg_package resource

[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
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • dpkg_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • options, package_name, 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

The dpkg_package 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

The dpkg_package resource has the following properties:

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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 'wget_1.13.4-2ubuntu1.4_amd64.deb' do
  source '/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb'
  action :install
end

dsc_resource 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.

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 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 resources 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
  module_version             String
  notifies                   # see description
  property                   Symbol
  resource                   String
  subscribes                 # see description
end

where:

  • dsc_resource is the resource.
  • name is the name given to 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, module_version, 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

The dsc_resource 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

The dsc_resource resource has the following properties:

ignore_failure

Ruby Type: true, false | Default Value: false

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

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.

module_version

Ruby Type: String

The version number of the module to use. PowerShell 5.0.10018.0 (or higher) supports having multiple versions of a module installed. This should be specified along with the module_name.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
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
False bool($false)
Fixnum Integer
Float Double
Hash Hashtable
True 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 unpack archive (.zip) files.
:environment Use to manage system environment variables.
:file Use to manage files and directories.
:group Use to manage local groups.
:log Use to log configuration messages.
:package Use to install and manage packages.
:registry Use to manage registry keys and registry key values.
:script Use to run PowerShell script blocks.
:service Use to manage services.
:user Use to manage local user accounts.
:windowsfeature Use to add or remove Windows features and roles.
:windowsoptionalfeature Use to configure Microsoft Windows optional features.
:windowsprocess Use 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 | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

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

Example to show usage of module properties

dsc_resource 'test-cluster' do
  resource :xCluster
  module_name 'xFailOverCluster'
  module_version '1.6.0.0'
  property :name, 'TestCluster'
  property :staticipaddress, '10.0.0.3'
  property :domainadministratorcredential, ps_credential('abcd')
end

dsc_script 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.

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 given to the resource block.
  • action identifies which 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

The dsc_script 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

The dsc_script 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' }).

ignore_failure

Ruby Type: true, false | Default Value: false

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

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

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: 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

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

execute resource

[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).

Changed in 12.19 to support windows alternate user identity in execute resources.

Syntax

An 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                true, false
  notifies                   # see description
  returns                    Integer, Array
  sensitive                  true, false
  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, 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

The execute 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 Type: 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 Type: String, Integer

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

ignore_failure

Ruby Type: true, false | Default Value: false

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

live_stream

Ruby Type: true, false | Default Value: false

Send the output of the command run by this execute resource block to the chef-client event stream.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

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.

sensitive

Ruby Type: true, false | Default Value: false

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Integer, Float

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

user

Ruby Type: 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 Type: 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 Type: 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 Type: 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 guard’s environment is inherited from the resource’s environment. For example:

execute 'bundle install' do
  cwd '/myapp'
  not_if 'bundle check' # This is run from /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:

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 the test from starting automatically, and then use the subscribes notification to run a configuration test when a change to the template is detected:

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 macOS

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 resource

[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              true, false
  backup                     false, Integer
  checksum                   String
  content                    String
  force_unlink               true, false
  group                      String, Integer
  inherits                   true, false
  manage_symlink_source      true, false
  mode                       String, Integer
  notifies                   # see description
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  rights                     Hash
  sensitive                  true, false
  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, 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

The file 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.

Properties

This resource has the following properties:

atomic_update

Ruby Type: true, false | Default Value: true

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.

backup

Ruby Type: false, Integer | Default Value: 5

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.

checksum

Ruby Type: 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 Type: true, false | Default Value: false

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.

group

Ruby Type: 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 Type: true, false | Default Value: false

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

inherits

Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

manage_symlink_source

Ruby Type: true, false | Default Value: true (with warning)

Change the behavior of the file resource if it is pointed at a symlink. When this value is set to true, the Chef client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to false, Chef will follow the symlink and will manage the permissions and content of symlink’s target file.

The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning.

mode

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

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

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

The syntax for notifies is:

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

Ruby Type: 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.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

rights

Ruby Type: 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 Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by the chef-client.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Block

Allows verification of a file’s contents before it is created. Creates a temporary file and then allows execution of commands or Ruby code. If this code evaluates to true, the file is created. If the code evaluates to false, an error is raised.

The types for this property are a block or a string. When specified as a block, it returns true or false. When specified as a string, it is executed as a system command. It evaluates to true if the command returns 0 as its exit status code and false if the command returns a non-zero exit status code.

Note

A block is arbitrary Ruby defined within the resource block by using the verify property. When a block returns 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 also return true:

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

In this example, the %{path} portion of this command is expanded to the temporary location where a copy of the file to be created exists. This will use Nginx’s syntax checking feature to ensure the file is a valid Nginx configuration file before writing the file. An error will be raised if the executed command returns a non-zero exit status code.

This should return true:

file '/tmp/foo' do
  content "hello"
  verify do |path|
    open(path).read.include? "hello"
  end
end

Whereas, this should return false:

file '/tmp/foo' do
  content "goodbye"
  verify do |path|
    open(path).read.include? "hello"
  end
end

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

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 resource

[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
  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, 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

The freebsd_package 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 Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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 resource

[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              true, false
  include_default_source     true, false
  gem_binary                 String
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  source                     String, Array
  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, include_default_source, gem_binary, options, package_name, 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 Chef 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 Type: true, false | Default Value: false

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

include_default_source

Ruby Type: true, false | Default Value: true

Set to false to not include Chef::Config[:rubygems_url] in the sources.

New in Chef Client 13.0

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 Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source

Ruby Type: String, Array

Optional. The URL, or list of URLs, at which the gem package is located. This list is added to the source configured in Chef::Config[:rubygems_url] (see also include_default_source) to construct the complete list of rubygems sources. Users in an “airgapped” environment should set Chef::Config[:rubygems_url] to their local RubyGems mirror.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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 gems file from the local file system

gem_package 'right_aws' do
  source '/tmp/right_aws-1.11.0.gem'
  action :install
end

Use the ignore_failure common attribute

gem_package 'syntax' do
  action :install
  ignore_failure true
end

git resource

[edit on GitHub]

Use the git resource to manage source control resources that exist in a git repository. git version 1.6.5 (or higher) is required to use all of the functionality in the git resource.

Syntax

A git resource block manages source control resources that exist in a git repository:

git "#{Chef::Config[:file_cache_path]}/app_name" do
  repository node[:app_name][:git_repository]
  revision node[:app_name][:git_revision]
  action :sync
end

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

git 'name' do
  additional_remotes      Hash
  checkout_branch         String # default value: deploy
  depth                   Integer
  destination             String # default value: 'name' unless specified
  enable_checkout         true, false # default value: true
  enable_submodules       true, false # default value: false
  environment             Hash, nil
  group                   String, Integer
  remote                  String # default value: origin
  repository              String
  revision                String # default value: HEAD
  ssh_wrapper             String
  timeout                 Integer
  user                    String, Integer
  action                  Symbol # defaults to :sync if not specified
end

where:

  • git is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • additional_remotes, checkout_branch, depth, destination, enable_checkout, enable_submodules, environment, group, remote, repository, revision, ssh_wrapper, timeout, and user are the properties available to this resource.

Actions

The git resource has the following actions:

:checkout
Clone or check out the source. When a checkout is available, this provider does nothing.
:export
Export the source, excluding or removing any version control artifacts.
: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.
:sync
Default. Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes.

Properties

The git resource has the following properties:

additional_remotes

Ruby Type: Hash

A Hash of additional remotes that are added to the git repository configuration.

checkout_branch

Ruby Type: String | Default Value: deploy

Do a one-time checkout from git or use when a branch in the upstream repository is named deploy. To prevent the git resource from attempting to check out master from master, set enable_checkout to false when using the checkout_branch property. See revision.

depth

Ruby Type: Integer

The number of past revisions to be included in the git shallow clone. The default behavior will do a full clone.

destination

Ruby Type: String

The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block. See “Syntax” section above for more information.

enable_checkout

Ruby Type: true, false | Default Value: true

Check out a repo from master. Set to false when using the checkout_branch attribute to prevent the git resource from attempting to check out master from master.

enable_submodules

Ruby Type: true, false | Default Value: false

Perform a sub-module initialization and update.

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.)

Note

The git provider automatically sets the ENV['HOME'] and ENV['GIT_SSH'] environment variables. To override this behavior and provide different values, add ENV['HOME'] and/or ENV['GIT_SSH'] to the environment Hash.

group

Ruby Type: String, Integer

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

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The alias for revision.

remote

Ruby Type: String

The remote repository to use when synchronizing an existing clone.

repository

Ruby Type: String

The URI for the git repository.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

revision

Ruby Type: String | Default Value: HEAD

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. See checkout_branch.

The value of the revision attribute may change over time. From one branch to another, to a tag, to a specific SHA for a commit, and then back to a branch. The revision attribute may even be changed in a way where history gets rewritten.

Instead of tracking a specific branch or doing a headless checkout, the chef-client maintains its own branch (via the git resource) that does not exist in the upstream repository. The chef-client is then free to forcibly check out this branch to any commit without destroying the local history of an existing branch.

For example, to explicitly track an upstream repository’s master branch:

revision 'master'

Use the git rev-parse and git ls-remote commands to verify that the chef-client is synchronizing commits correctly. (The chef-client always runs git ls-remote on the upstream repository to verify the commit is made to the correct repository.)

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.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Integer

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

user

Ruby Type: String, Integer

The system user that is responsible for the checked-out code. Default value: the home directory of this user, as indicated by the HOME environment variable.

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 the git mirror

git '/opt/mysources/couch' do
  repository 'git://git.apache.org/couchdb.git'
  revision 'master'
  action :sync
end

Use different branches

To use different branches, depending on the environment of the node:

if node.chef_environment == 'QA'
   branch_name = 'staging'
else
   branch_name = 'master'
end

git '/home/user/deployment' do
   repository 'git@github.com:gitsite/deployment.git'
   revision branch_name
   action :sync
   user 'user'
   group 'test'
end

where the branch_name variable is set to staging or master, depending on the environment of the node. Once this is determined, the branch_name variable is used to set the revision for the repository. If the git status command is used after running the example above, it will return the branch name as deploy, as this is the default value. Run the chef-client in debug mode to verify that the correct branches are being checked out:

$ sudo chef-client -l debug

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.

Upgrade packages from git

The following example uses the git resource to upgrade packages:

# the following code sample comes from the ``source`` recipe
# in the ``libvpx-cookbook`` cookbook:
# https://github.com/enmasse-entertainment/libvpx-cookbook

git "#{Chef::Config[:file_cache_path]}/libvpx" do
  repository node[:libvpx][:git_repository]
  revision node[:libvpx][:git_revision]
  action :sync
  notifies :run, 'bash[compile_libvpx]', :immediately
end

Pass in environment variables

git '/opt/mysources/couch' do
  repository 'git://git.apache.org/couchdb.git'
  revision 'master'
  environment 'VAR' => 'whatever'
  action :sync
end

group resource

[edit on GitHub]

Use the group resource to manage a local group.

Syntax

The group resource has the following syntax:

group 'name' do
  append                true, false # default value: false
  excluded_members      String, Array
  gid                   String, Integer
  group_name            String # default value: 'name' unless specified
  members               String, Array
  non_unique            true, false # default value: false
  system                true, false # default value: false
  action                Symbol # defaults to :create if not specified
end

where:

  • group is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • append, excluded_members, gid, group_name, members, non_unique, and system are the properties available to this resource.

Actions

The group resource has the following actions:

:create
Default. Create a group. If a group already exists (but does not match), update that group to match.
:manage
Manage an existing group. This action does nothing if the group does not exist.
:modify
Modify an existing group. This action raises an exception if the group does not exist.
: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 group.

Properties

The group resource has the following properties:

append

Ruby Type: true, false | Default Value: false

How members should be appended and/or removed from a group. When true, members are appended and excluded_members are removed. When false, group members are reset to the value of the members property.

excluded_members

Ruby Type: String, Array

Remove users from a group. May only be used when append is set to true.

gid

Ruby Type: String, Integer

The identifier for the group.

group_name

Ruby Type: String | Default Value: 'name'

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

ignore_failure

Ruby Type: true, false | Default Value: false

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

members

Ruby Type: Array

Which users should be set or appended to a group. When more than one group member is identified, the list of members should be an array: members ['user1', 'user2'].

non_unique

Ruby Type: true, false | Default Value: false

Allow gid duplication. May only be used with the Groupadd provider.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: true, false | Default Value: false

Set if a group belongs to a system group. Set to true if the group belongs to a system group.

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.

Append users to groups

group 'www-data' do
  action :modify
  members 'maintenance'
  append true
end

Add a user to group on the Windows platform

group 'Administrators' do
  members ['domain\foo']
  append true
  action :modify
end

homebrew_cask resource

[edit on GitHub]

Use the homebrew_cask resource to install binaries distributed via the Homebrew package manager.

New in Chef Client 14.0.

Syntax

The homebrew_cask resource has the following syntax:

homebrew_cask 'name' do
  cask_name          String # default value: 'name' unless specified
  homebrew_path      String # default value: /usr/local/bin/brew
  install_cask       true, false # default value: true
  options            String
  owner              String
  action             Symbol # defaults to :install if not specified
end

where:

  • homebrew_cask is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • cask_name, homebrew_path, install_cask, options, and owner are the properties available to this resource.

Actions

The homebrew_cask resource has the following actions:

:install
Default. Install an application that is packaged as a Homebrew cask.
:remove
Remove an application that is packaged as a Homebrew cask.
: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

cask_name

Ruby Type: String | Default Value: 'name'

The name of the Homebrew cask, if it differs from the resource block name.

homebrew_path

Ruby Type: String | Default Value: /usr/local/bin/brew

The path to the Homebrew binary.

install_cask

Ruby Type: true, false | Default Value: true

Automatically install the Homebrew cask tap, if necessary.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

Options to pass to the brew command during installation.

owner

Ruby Type: String

The owner of the Homebrew installation.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

homebrew_package resource

[edit on GitHub]

Use the homebrew_package resource to manage packages for the macOS 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 homebrew_package resource block manages a package on a node, typically by installing it. The simplest use of the homebrew_package resource is:

homebrew_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 homebrew_package resource is:

homebrew_package 'name' do
  homebrew_user              String, Integer
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where

  • homebrew_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
  • homebrew_user, options, package_name, 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:

homebrew_user

Ruby Type: String, Integer

The name of the Homebrew owner to be used by the chef-client when executing a command.

The chef-client, by default, will attempt to execute a Homebrew command as the owner of /usr/local/bin/brew. If that executable does not exist, the chef-client will attempt to find the user by executing which brew. If that executable cannot be found, the chef-client will print an error message: Could not find the "brew" executable in /usr/local/bin or anywhere on the path.. Use the homebrew_user attribute to specify the Homebrew owner for situations where the chef-client cannot automatically detect the correct owner.

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

homebrew_package 'name of package' do
  action :install
end

Specify the Homebrew user with a UUID

homebrew_package 'emacs' do
  homebrew_user 1001
end

Specify the Homebrew user with a string

homebrew_package 'vim' do
  homebrew_user 'user1'
end

homebrew_tap resource

[edit on GitHub]

Use the homebrew_tap resource to add additional formula repositories to the Homebrew package manager.

New in Chef Client 14.0.

Syntax

The homebrew_tap resource has the following syntax:

homebrew_tap 'name' do
  full               true, false # default value: false
  homebrew_path      String # default value: /usr/local/bin/brew
  owner              String
  tap_name           String # default value: 'name' unless specified
  url                String
  action             Symbol # defaults to :tap if not specified
end

where:

  • homebrew_tap is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • full, homebrew_path, owner, tap_name, and url are the properties available to this resource.

Actions

The homebrew_tap resource has the following actions:

:tap
Default. Add a Homebrew tap.
:untap
Remove a Homebrew tap.
: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

The homebrew_tap resource has the following properties:

full

Ruby Type: true, false | Default Value: false

Perform a full clone on the tap, as opposed to a shallow clone.

homebrew_path

Ruby Type: String | Default Value: /usr/local/bin/brew

The path to the Homebrew binary.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String | Default Value: Calculated default username

The owner of the Homebrew installation.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String | Default Value: 'name'

The name of the Homebrew tap, if it differs from the resource block name. Homebrew tap names must be in the form of REPO/TAP.

url

Ruby Type: String

The URL of the tap.

hostname resource

[edit on GitHub]

Use the hostname resource to set the system’s hostname, configure hostname and hosts config file, and re-run the Ohai hostname plugin so the hostname will be available in subsequent cookbooks.

New in Chef Client 14.0.

Syntax

The hostname resource has the following syntax:

hostname 'name' do
  aliases             Array, nil
  compile_time        true, false # default value: true
  hostname            String # default value: 'name' unless specified
  ipaddress           String
  windows_reboot      true, false # default value: true
  action              Symbol # defaults to :set if not specified
end

where:

  • hostname is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • aliases, compile_time, hostname, ipaddress, and windows_reboot are the properties available to this resource.

Actions

The hostname resource has the following actions:

:set
Default action. Set the node’s hostname.
: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

The hostname resource has the following properties:

aliases

Ruby Type: Array, nil | Default Value: nil

An array of hostname aliases to use when configuring the hosts file.

compile_time

Ruby Type: true, false | Default Value: true

Determines whether or not the resource shoul be run at compile time.

hostname

Ruby Type: String | Default Value: 'name'

Used to specify the hostname if it is different than the resource’s name.

ipaddress

Ruby Type: String | Default Value: node["ipaddress"]

The IP address to use when configuring the hosts file. By default, this uses node["ipaddress"] information collected by Ohai.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: true, false | Default Value: true

Determines whether or not Windows should be reboot after changing the hostname, as this is required for the change to take effect.

Examples

Set the hostname

hostname 'example' do

The example above sets the hostname to example for the IP address, as detected by Ohai.

Manually specify the hostname and IP address

hostname 'statically_configured_host' do
  hostname 'example'
  ipaddress '198.51.100.2'
end

http_request resource

[edit on GitHub]

Use the http_request resource to send an HTTP request (GET, PUT, POST, DELETE, HEAD, or OPTIONS) with an arbitrary message. This resource is often useful when custom callbacks are necessary.

Syntax

A http_request resource block sends HTTP requests with an arbitrary message. For example, send a DELETE request to 'http://www.chef.io/some_page?message=please_delete_me'.

http_request 'please_delete_me' do
  url 'http://www.chef.io/some_page'
  action :delete
end

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

http_request 'name' do
  headers                    Hash
  message                    Object # defaults to 'name' if not specified
  notifies                   # see description
  subscribes                 # see description
  url                        String
  action                     Symbol # defaults to :get if not specified
end

where:

  • http_request is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • headers, message, and url are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions

The http_request resource has the following actions:

:delete
Send a DELETE request.
:get

Default. Send a GET request.

Changed in Chef Client 12.0 to deprecate the hard-coded query string from earlier versions. Cookbooks that rely on this string need to be updated to manually add it to the URL as it is passed to the resource.

:head
Send a HEAD request.
: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.
:options
Send an OPTIONS request.
:post
Send a POST request.
:put
Send a PUT request.

Properties

The http_request resource has the following properties:

headers

Ruby Type: Hash

A Hash of custom headers.

ignore_failure

Ruby Type: true, false | Default Value: false

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

message

Ruby Type: Object

The message that is sent by the HTTP request. 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 notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String

The URL to which an HTTP request is sent.

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.

Send a GET request

http_request 'some_message' do
  url 'http://example.com/check_in'
end

The message is sent as http://example.com/check_in?message=some_message.

Send a POST request

To send a POST request as JSON data, convert the message to JSON and include the correct content-type header. For example:

http_request 'posting data' do
  action :post
  url 'http://example.com/check_in'
  message ({:some => 'data'}.to_json)
  headers({'AUTHORIZATION' => "Basic #{
    Base64.encode64('username:password')}",
    'Content-Type' => 'application/data'
  })
end

Transfer a file only when the 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

ifconfig resource

[edit on GitHub]

Use the ifconfig resource to manage interfaces on Unix and Linux systems.

Syntax

An ifconfig resource block manages interfaces, such as a static IP address:

ifconfig '33.33.33.80' do
  device 'eth1'
end

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

ifconfig 'name' do
  bcast             String
  bonding_opts      String
  bootproto         String
  device            String
  ethtool_opts      String
  family            String # default value: inet
  gateway           String
  hwaddr            String
  inet_addr         String
  mask              String
  master            String
  metric            String
  mtu               String
  network           String
  onboot            String
  onparent          String
  slave             String
  target            String # default value: 'name' unless specified
  vlan              String
  action            Symbol # defaults to :add if not specified
end

where:

  • ifconfig is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • bcast, bonding_opts, bootproto, device, ethtool_opts, family, gateway, hwaddr, inet_addr, mask, master, metric, mtu, network, onboot, onparent, slave, target, and vlan are the properties available to this resource.

Actions

The ifconfig resource has the following actions:

:add
Default. Run ifconfig to configure a network interface and (on some platforms) write a configuration file for that network interface.
:delete
Run ifconfig to disable a network interface and (on some platforms) delete that network interface’s configuration file.
:disable
Run ifconfig to disable a network interface.
:enable
Run ifconfig to enable a network interface.
: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

The ifconfig resource has the following properties:

bcast

Ruby Type: String

The broadcast address for a network interface. On some platforms this property is not set using ifconfig, but instead is added to the startup configuration file for the network interface.

bonding_opts

Ruby Type: String

Bonding options to pass via BONDING_OPTS on RHEL and CentOS. For example: mode=active-backup miimon=100

New in Chef Client 13.4.

bootproto

Ruby Type: String

The boot protocol used by a network interface.

device

Ruby Type: String

The network interface to be configured.

ethtool_opts

Ruby Type: String

Options to be passed to ethtool(8). For example: -A eth0 autoneg off rx off tx off

New in Chef Client 13.4.

family

Ruby Type: String | Default Value: inet

Networking family option for Debian-based systems; for example: inet or inet6.

New in Chef Client 14.0.

gateway

Ruby Type: String

The gateway to use for the interface.

New in Chef Client 14.4.

hwaddr

Ruby Type: String

The hardware address for the network interface.

ignore_failure

Ruby Type: true, false | Default Value: false

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

inet_addr

Ruby Type: String

The Internet host address for the network interface.

mask

Ruby Type: String

The decimal representation of the network mask. For example: 255.255.255.0.

master

Ruby Type: String

Specifies the channel bonding interface to which the Ethernet interface is linked.

New in Chef Client 13.4.

metric

Ruby Type: String

The routing metric for the interface.

mtu

Ruby Type: String

The maximum transmission unit (MTU) for the network interface.

network

Ruby Type: String

The address for the network interface.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

Bring up the network interface on boot.

onparent

Ruby Type: String

Bring up the network interface when its parent interface is brought up.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String

When set to yes, this device is controlled by the channel bonding interface that is specified via the master property.

New in Chef Client 13.4.

target

Ruby Type: String | Default Value: 'name'

The IP address that is to be assigned to the network interface. Default value: the name of the resource block. See “Syntax” section above for more information.

vlan

Ruby Type: String

The VLAN to assign the interface to. New in Chef Client 14.4.

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.

Configure a network interface

ifconfig "33.33.33.80" do
  bootproto "dhcp"
  device "eth1"
end

will create the following interface:

vagrant@default-ubuntu-1204:~$ cat /etc/network/interfaces.d/ifcfg-eth1
iface eth1 inet dhcp

Specify a boot protocol

ifconfig '192.186.0.1' do
  device 'eth0'
end

Specify a static IP address

ifconfig "33.33.33.80" do
  device "eth1"
end

will create the following interface:

iface eth1 inet static
  address 33.33.33.80

Update a static IP address with a boot protocol

ifconfig "33.33.33.80" do
  bootproto "dhcp"
  device "eth1"
end

will update the interface from static to dhcp:

iface eth1 inet dhcp
  address 33.33.33.80

ips_package resource

[edit on GitHub]

Use the ips_package resource to manage packages (using Image Packaging System (IPS)) on the Solaris 11 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 ips_package resource block manages a package on a node, typically by installing it. The simplest use of the ips_package resource is:

ips_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 ips_package resource is:

ips_package 'name' do
  accept_license             true, false
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • ips_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • accept_license, options, package_name, 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

The ips_package 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.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties

The ips_package resource has the following properties:

accept_license

Ruby Type: true, false | Default Value: false

Accept an end-user license agreement, automatically.

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: 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 declare_resource. This replaces all previous use cases where the provider class was passed in through the provider property:

    pkg_resource = case node['platform_family']
      when 'debian'
        :dpkg_package
      when 'fedora', 'rhel', 'amazon'
        :rpm_package
      end
    
    pkg_path = (pkg_resource == :dpkg_package) ? '/tmp/foo.deb' : '/tmp/foo.rpm'
    
    declare_resource(pkg_resource, pkg_path) do
      action :install
    end
    

For reference, the providers available for this resource are listed below. However please note that specifying a provider via its long name (such as Chef::Provider::Package) using the provider property is not recommended. If a provider needs to be called manually, use one of the two approaches detailed above.

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::Ips, ips_package
The provider for the ips 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

ips_package 'name of package' do
  action :install
end

kernel_module resource

[edit on GitHub]

Use the kernel_module resource to manage kernel modules on Linux systems. This resource can load, unload, blacklist, install, and uninstall modules.

New in Chef Client 14.3.

Syntax

The kernel_module resource has the following syntax:

kernel_module 'name' do
  load_dir        String # default value: /etc/modules-load.d
  modname         String # default value: 'name' unless specified
  unload_dir      String # default value: /etc/modprobe.d
  action          Symbol # defaults to :install if not specified
end

where:

  • kernel_module is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • load_dir, modname, and unload_dir are the properties available to this resource.

Actions

The kernel_module resource has the following actions:

:blacklist
Blacklist a kernel module.
:install
Default. Load kernel module, and ensure it loads on reboot.
:load
Load a kernel module.
:uninstall
Unload a kernel module and remove module config, so it doesn’t load on reboot.
:unload
Unload kernel module.
: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

The kernel_module resource has the following properties:

load_dir

Ruby Type: String | Default Value: /etc/modules-load.d

The directory to load modules from.

modname

Ruby Type: String | Default Value: 'name'

The name of the kernel 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 notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String | Default Value: /etc/modprobe.d

The modprobe.d directory.

ksh resource

[edit on GitHub]

Use the ksh resource to execute scripts using the Korn shell (ksh) 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. New in Chef Client 12.6.

Note

The ksh 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 ksh resource block executes scripts using ksh:

ksh '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 ksh resource is:

ksh 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  notifies                   # see description
  path                       Array
  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:

  • ksh is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • code, creates, cwd, environment, flags, group, path, 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

The ksh 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 Type: String, Integer

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

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
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:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

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.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Integer, Float | Default Value: 3600

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

user

Ruby Type: String, Integer

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

umask

Ruby Type: 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

Examples

None.

launchd resource

[edit on GitHub]

Use the launchd resource to manage system-wide services (daemons) and per-user services (agents) on the macOS platform.

New in Chef Client 12.8.

Syntax

The launchd resource has the following syntax:

launchd 'name' do
  abandon_process_group           true, false
  backup                          Integer, false
  cookbook                        String
  debug                           true, false
  disabled                        true, false # default value: false
  enable_globbing                 true, false
  enable_transactions             true, false
  environment_variables           Hash
  exit_timeout                    Integer
  group                           String, Integer
  hard_resource_limits            Hash
  inetd_compatibility             Hash
  init_groups                     true, false
  keep_alive                      true, false, Hash
  label                           String # default value: 'name' unless specified
  launch_only_once                true, false
  ld_group                        String
  limit_load_from_hosts           Array
  limit_load_to_hosts             Array
  limit_load_to_session_type      Array, String
  low_priority_io                 true, false
  mach_services                   Hash
  mode                            String, Integer
  nice                            Integer
  on_demand                       true, false
  owner                           String, Integer
  path                            String
  plist_hash                      Hash
  process_type                    String
  program                         String
  program_arguments               Array
  queue_directories               Array
  root_directory                  String
  run_at_load                     true, false
  session_type                    String
  sockets                         Hash
  soft_resource_limits            Array
  source                          String
  standard_error_path             String
  standard_in_path                String
  standard_out_path               String
  start_calendar_interval         Hash, Array
  start_interval                  Integer
  start_on_mount                  true, false
  throttle_interval               Integer
  time_out                        Integer
  type                            String # default value: daemon
  umask                           Integer
  username                        String
  wait_for_debugger               true, false
  watch_paths                     Array
  working_directory               String
  action                          Symbol # defaults to :create if not specified
end

where:

  • launchd is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • abandon_process_group, backup, cookbook, debug, disabled, enable_globbing, enable_transactions, environment_variables, exit_timeout, group, hard_resource_limits, inetd_compatibility, init_groups, keep_alive, label, launch_only_once, ld_group, limit_load_from_hosts, limit_load_to_hosts, limit_load_to_session_type, low_priority_io, mach_services, mode, nice, on_demand, owner, path, plist_hash, process_type, program, program_arguments, queue_directories, root_directory, run_at_load, session_type, sockets, soft_resource_limits, source, standard_error_path, standard_in_path, standard_out_path, start_calendar_interval, start_interval, start_on_mount, throttle_interval, time_out, type, umask, username, wait_for_debugger, watch_paths, and working_directory are the properties available to this resource.

Actions

The launchd resource has the following actions:

:create
Default. Create a launchd property list.
:create_if_missing
Create a launchd property list, if it does not already exist.
:delete
Delete a launchd property list. This will unload a daemon or agent, if loaded.
:disable
Disable a launchd property list.
:enable
Create a launchd property list, and then ensure that it is enabled. If a launchd property list already exists, but does not match, updates the property list to match, and then restarts the daemon or agent.
:restart
Restart a launchd managed daemon or agent.

Properties

This resource has the following properties:

backup

Ruby Type: Integer, false

The number of backups to be kept in /var/chef/backup. Set to false to prevent backups from being kept.

cookbook

Ruby Type: String

The name of the cookbook in which the source files are located.

group

Ruby Type: String, Integer

When launchd is run as the root user, the group to run the job as. If the username property is specified and this property is not, this value is set to the default group for the user.

ignore_failure

Ruby Type: true, false | Default Value: false

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

label

Ruby Type: String

The unique identifier for the job.

mode

Ruby Type: Integer, String | Default Value: '0755'

A quoted 3-5 character string that defines the octal mode. For example: '755', '0755', or 00755.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: 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.

plist_hash

Ruby Type: Hash

A Hash of key value pairs used to create the launchd property list.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

session_type

Ruby Type: String

The type of launchd plist to be created. Possible values: system (default) or user.

source

Ruby Type: String

The path to the launchd property list.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Hash

Specify a Hash of supported mount features. Default value: remount: false.

type

Ruby Type: String

The type of resource. Possible values: daemon (default), agent.

The following resource properties may be used to define keys in the XML property list for a daemon or agent. Please refer to the Apple man page documentation for launchd for more information about these keys:

abandon_process_group

Ruby Type: true, false

If a job dies, all remaining processes with the same process ID may be kept running. Set to true to kill all remaining processes.

debug

Ruby Type: true, false

Sets the log mask to LOG_DEBUG for this job.

disabled

Ruby Type: true, false| Default Value: false

Hints to launchctl to not submit this job to launchd.

enable_globbing

Ruby Type: true, false

Update program arguments before invocation.

enable_transactions

Ruby Type: true, false

Track in-progress transactions; if none, then send the SIGKILL signal.

environment_variables

Ruby Type: Hash

Additional environment variables to set before running a job.

exit_timeout

Ruby Type: Integer | Default Value: 20

The amount of time (in seconds) launchd waits before sending a SIGKILL signal.

hard_resource_limits

Ruby Type: Hash

A Hash of resource limits to be imposed on a job.

inetd_compatibility

Ruby Type: Hash

Specifies if a daemon expects to be run as if it were launched from inetd. Set to wait => true to pass standard input, output, and error file descriptors. Set to wait => false to call the accept system call on behalf of the job, and then pass standard input, output, and error file descriptors.

init_groups

Ruby Type: true, false | Default Value: true

Specify if initgroups is called before running a job.

keep_alive

Ruby Type: true, false, Hash | Default Value: false

Keep a job running continuously (true) or allow demand and conditions on the node to determine if the job keeps running (false).

launch_only_once

Ruby Type: true, false

Specify if a job can be run only one time. Set this value to true if a job cannot be restarted without a full machine reboot.

limit_load_from_hosts

Ruby Type: Array

An array of hosts to which this configuration file does not apply, i.e. “apply this configuration file to all hosts not specified in this array”.

limit_load_to_hosts

Ruby Type: Array

An array of hosts to which this configuration file applies.

limit_load_to_session_type

Ruby Type: Array, String

The session type(s) to which this configuration file applies.

low_priority_io

Ruby Type: true, false

Specify if the kernel on the node should consider this daemon to be low priority during file system I/O.

mach_services

Ruby Type: Hash

Specify services to be registered with the bootstrap subsystem.

nice

Ruby Type: Integer

The program scheduling priority value in the range -20 to 20.

on_demand

Ruby Type: true, false

Keep a job alive. Only applies to macOS version 10.4 (and earlier); use keep_alive instead for newer versions.

process_type

Ruby Type: String

The intended purpose of the job: Adaptive, Background, Interactive, or Standard.

program

Ruby Type: String

The first argument of execvp, typically the file name associated with the file to be executed. This value must be specified if program_arguments is not specified, and vice-versa.

program_arguments

Ruby Type: Array

The second argument of execvp. If program is not specified, this property must be specified and will be handled as if it were the first argument.

queue_directories

Ruby Type: Array

An array of non-empty directories which, if any are modified, will cause a job to be started.

root_directory

Ruby Type: String

chroot to this directory, and then run the job.

run_at_load

Ruby Type: true, false | Default Value: false

Launch a job once (at the time it is loaded).

sockets

Ruby Type: Hash

A Hash of on-demand sockets that notify launchd when a job should be run.

soft_resource_limits

Ruby Type: Array

A Hash of resource limits to be imposed on a job.

standard_error_path

Ruby Type: String

The file to which standard error (stderr) is sent.

standard_in_path

Ruby Type: String

The file to which standard input (stdin) is sent.

standard_out_path

Ruby Type: String

The file to which standard output (stdout) is sent.

start_calendar_interval

Ruby Type: Hash

A Hash (similar to crontab) that defines the calendar frequency at which a job is started. For example: { Minute => "0", Hour => "20", Day => "*", Weekday => "1-5", Month => "*" } will run a job at 8:00 PM every day, Monday through Friday, every month of the year.

start_interval

Ruby Type: Integer

The frequency (in seconds) at which a job is started.

start_on_mount

Ruby Type: true, false

Start a job every time a file system is mounted.

throttle_interval

Ruby Type: Integer | Default Value: 10

The frequency (in seconds) at which jobs are allowed to spawn.

time_out

Ruby Type: Integer

The amount of time (in seconds) a job may be idle before it times out. If no value is specified, the default timeout value for launchd will be used.

umask

Ruby Type: Integer

A decimal value to pass to umask before running a job.

username

Ruby Type: String

When launchd is run as the root user, the user to run the job as.

wait_for_debugger

Ruby Type: true, false

Specify if launchd has a job wait for a debugger to attach before executing code.

watch_paths

Ruby Type: Array

An array of paths which, if any are modified, will cause a job to be started.

working_directory

Ruby Type: String

chdir to this directory, and then run the job.

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 Launch Daemon from a cookbook file

launchd 'com.chef.every15' do
  source 'com.chef.every15.plist'
end

Create a Launch Daemon using keys

launchd 'call.mom.weekly' do
  program '/Library/scripts/call_mom.sh'
  start_calendar_interval 'Weekday' => 7, 'Hourly' => 10
  time_out 300
end

Remove a Launch Daemon

launchd 'com.chef.every15' do
  action :delete
end

locale resource

[edit on GitHub]

Use the locale resource to set the system’s locale.

New in Chef Client 14.5.

Syntax

The locale resource has the following syntax:

locale 'name' do
  lang        String # default value: en_US.utf8
  lc_all      String # default value: en_US.utf8
  action      Symbol # defaults to :update if not specified
end

where:

  • locale is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • lang and lc_all are the properties available to this resource.

Actions

The locale resource has the following actions:

:update
Updates the system’s locale.
: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

The locale resource has the following properties:

lang

Ruby Type: String | Default Value: en_US.utf8

Sets the default system language.

lc_all

Ruby Type: String | Default Value: en_US.utf8

Sets the fallback system language.

Common Resource Functionality

Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

ignore_failure

Ruby Type: true, false | Default Value: false

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by the chef-client.

Notifications

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

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.

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.

log resource

[edit on GitHub]

Use the log resource to create log entries. The log resource behaves like any other resource: built into the resource collection during the compile phase, and then run during the execution phase. (To create a log entry that is not built into the resource collection, use Chef::Log instead of the log resource.)

Note

By default, every log resource that executes will count as an updated resource in the updated resource count at the end of a Chef run. You can disable this behavior by adding count_log_resource_updates false to your Chef client.rb configuration file.

Syntax

A log resource block adds messages to the log file based on events that occur during the Chef Client run:

log 'message' do
  message 'A message add to the log.'
  level :info
end

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

log 'name' do
  level        Symbol # default value: info
  message      String # default value: 'name' unless specified
  action       Symbol # defaults to :write if not specified
end

where:

  • log is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • level and message are the properties available to this resource.

Actions

The log 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.
:write
Default. Write to log.

Properties

The log resource has the following properties:

ignore_failure

Ruby Type: true, false | Default Value: false

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

level

Ruby Type: Symbol | Default Value: :info

The logging level for displaying this message.. Options (in order of priority): :debug, :info, :warn, :error, and :fatal.

message

Ruby Type: String

The message to be added to a log file. 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 notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Chef::Log Entries

Chef::Log extends Mixlib::Log and will print log entries to the default logger that is configured for the machine on which the Chef Client is running. (To create a log entry that is built into the resource collection, use the log resource instead of Chef::Log.)

The following log levels are supported:

Log Level Syntax
Fatal Chef::Log.fatal('string')
Error Chef::Log.error('string')
Warn Chef::Log.warn('string')
Info Chef::Log.info('string')
Debug Chef::Log.debug('string')

Note

The parentheses are optional, e.g. Chef::Log.info 'string' may be used instead of Chef::Log.info('string').

The following example shows a series of fatal Chef::Log entries:

unless node['splunk']['upgrade_enabled']
  Chef::Log.fatal('The chef-splunk::upgrade recipe was added to the node,')
  Chef::Log.fatal('but the attribute `node["splunk"]["upgrade_enabled"]` was not set.')
  Chef::Log.fatal('I am bailing here so this node does not upgrade.')
  raise
end

service 'splunk_stop' do
  service_name 'splunk'
  supports status: true
  action :stop
end

if node['splunk']['is_server']
  splunk_package = 'splunk'
  url_type = 'server'
else
  splunk_package = 'splunkforwarder'
  url_type = 'forwarder'
end

splunk_installer splunk_package do
  url node['splunk']['upgrade']["#{url_type}_url"]
end

if node['splunk']['accept_license']
  execute 'splunk-unattended-upgrade' do
    command "#{splunk_cmd} start --accept-license --answer-yes"
  end
else
  Chef::Log.fatal('You did not accept the license (set node["splunk"]["accept_license"] to true)')
  Chef::Log.fatal('Splunk is stopped and cannot be restarted until the license is accepted!')
  raise
end

The full recipe is the upgrade.rb recipe of the chef-splunk cookbook that is maintained by Chef.

The following example shows using multiple Chef::Log entry types:

...

begin
  aws = Chef::DataBagItem.load(:aws, :main)
  Chef::Log.info("Loaded AWS information from DataBagItem aws[#{aws['id']}]")
rescue
  Chef::Log.fatal("Could not find the 'main' item in the 'aws' data bag")
  raise
end

...

The full recipe is in the ebs_volume.rb recipe of the database cookbook that is maintained by Chef.

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 default logging level

log 'a string to log'

Set debug logging level

log 'a debug string' do
  level :debug
end

Add a message to a log file

log 'message' do
  message 'This is the message that will be added to the log.'
  level :info
end

macos_userdefaults resource

[edit on GitHub]

Use the macos_userdefaults resource to manage the macOS user defaults system. The properties of the resource are passed to the defaults command, and the parameters follow the conventions of that command. See the defaults man page for additional information.

New in Chef Client 14.0.

Syntax

The macos_userdefaults resource has the following syntax:

macos_userdefaults 'name' do
  domain                String # required
  global                true, false # default value: 'false'
  key                   String
  notifies              # see description
  subscribes            # see description
  sudo                  true, false # default value: 'false'
  type                  String # default value: ""
  user                  String
  value                 Integer, Float, String, true, false, Hash, Array
  action                Symbol # defaults to :write if not specified
end

where:

  • macos_userdefaults is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • domain, global, is_set, key, sudo, type, user, and value are the properties available to this resource.

Actions

The macos_userdefaults resource has the following actions:

:write
Default. Writes the setting to the specified domain.
: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

The macos_userdefaults resource has the following properties:

domain

Ruby Type: String | REQUIRED

The domain that the user defaults belong to.

global

Ruby Type: true, false | Default Value: false

Determines whether or not the domain is global.

key

Ruby Type: String

The preference key.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: true, false | Default Value: false

Set to true if the setting you wish to modify requires privileged access.

type

Ruby Type: String | Default Value: ""

The value type of the preference key.

user

Ruby Type: String

The system user that the default will be applied to.

value

Ruby Type: Integer, Float, String, true, false, Hash, Array | REQUIRED

The value of the key.

Examples

Specify a global domain

macos_userdefaults 'full keyboard access to all controls' do
  domain 'AppleKeyboardUIMode'
  global true
  value '2'
end

Use an integer value

macos_userdefaults 'enable macOS firewall' do
  domain '/Library/Preferences/com.apple.alf'
  key 'globalstate'
  value '1'
  type 'int'
end

Use a boolean value

macos_userdefaults 'finder expanded save dialogs' do
  domain 'NSNavPanelExpandedStateForSaveMode'
  global true
  value 'TRUE'
  type 'bool'
end

macports_package resource

[edit on GitHub]

Use the macports_package resource to manage packages for the macOS 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 macports_package resource block manages a package on a node, typically by installing it. The simplest use of the macports_package resource is:

macports_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 macports_package resource is:

macports_package 'name' do
  notifies                   # see description
  options                    String
  package_name               String
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • macports_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • options, package_name, 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

The macports_package 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:

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

macports_package 'name of package' do
  action :install
end

mdadm resource

[edit on GitHub]

Use the mdadm resource to manage RAID devices in a Linux environment using the mdadm utility. The mdadm resource will create and assemble an array, but it will not create the config file that is used to persist the array upon reboot. If the config file is required, it must be done by specifying a template with the correct array layout, and then by using the mount resource to create a file systems table (fstab) entry.

Syntax

The mdadm resource has the following syntax:

mdadm 'name' do
  bitmap           String
  chunk            Integer # default value: 16
  devices          Array
  exists           true, false # default value: false
  layout           String
  level            Integer # default value: 1
  metadata         String # default value: 0.90
  raid_device      String # default value: 'name' unless specified
  action           Symbol # defaults to :create if not specified
end

where:

  • mdadm is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • bitmap, chunk, devices, exists, layout, level, metadata, and raid_device are the properties available to this resource.

Actions

The mdadm resource has the following actions:

:assemble
Assemble a previously created array into an active array.
:create
Default. Create an array with per-device superblocks. If an array already exists (but does not match), update that array to match.
: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.
:stop
Stop an active array.

Properties

The mdadm resource has the following properties:

bitmap

Ruby Type: String

The path to a file in which a write-intent bitmap is stored.

chunk

Ruby Type: Integer | Default Value: 16

The chunk size. This property should not be used for a RAID 1 mirrored pair (i.e. when the level property is set to 1).

devices

Ruby Type: Array

The devices to be part of a RAID array.

exists

Ruby Type: true, false | Default Value: false

Indicates whether the RAID array exists.

ignore_failure

Ruby Type: true, false | Default Value: false

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

layout

Ruby Type: String

The RAID5 parity algorithm. Possible values: left-asymmetric (or la), left-symmetric (or ls), right-asymmetric (or ra), or right-symmetric (or rs).

level

Ruby Type: Integer | Default Value: 1

The RAID level.

metadata

Ruby Type: String | Default Value: 0.90

The superblock type for RAID metadata.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

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 and assemble a RAID 0 array

The mdadm command can be used to create RAID arrays. For example, a RAID 0 array named /dev/md0 with 10 devices would have a command similar to the following:

$ mdadm --create /dev/md0 --level=0 --raid-devices=10 /dev/s01.../dev/s10

where /dev/s01 .. /dev/s10 represents 10 devices (01, 02, 03, and so on). This same command, when expressed as a recipe using the mdadm resource, would be similar to:

mdadm '/dev/md0' do
  devices [ '/dev/s01', ... '/dev/s10' ]
  level 0
  action :create
end

(again, where /dev/s01 .. /dev/s10 represents devices /dev/s01, /dev/s02, /dev/s03, and so on).

Create and assemble a RAID 1 array

mdadm '/dev/md0' do
  devices [ '/dev/sda', '/dev/sdb' ]
  level 1
  action [ :create, :assemble ]
end

Create and assemble a RAID 5 array

The mdadm command can be used to create RAID arrays. For example, a RAID 5 array named /dev/sd0 with 4, and a superblock type of 0.90 would be similar to:

mdadm '/dev/sd0' do
  devices [ '/dev/s1', '/dev/s2', '/dev/s3', '/dev/s4' ]
  level 5
  metadata '0.90'
  chunk 32
  action :create
end

mount resource

[edit on GitHub]

Use the mount resource to manage a mounted file system.

Syntax

The mount resource has the following syntax:

mount 'name' do
  device           String
  device_type      String, Symbol # default value: device
  domain           String
  dump             Integer, false # default value: 0
  enabled          true, false # default value: false
  fsck_device      String # default value: -
  fstype           String, nil # default value: auto
  mount_point      String # default value: 'name' unless specified
  mounted          true, false # default value: false
  options          Array, String, nil # default value: ["defaults"]
  pass             Integer, false # default value: 2
  password         String
  supports         Hash
  username         String
  action           Symbol # defaults to :mount if not specified
end

where:

  • mount is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • device, device_type, domain, dump, enabled, fsck_device, fstype, mount_point, mounted, options, pass, password, supports, and username are the properties available to this resource.

Actions

The mount resource has the following actions:

:disable
Remove an entry from the file systems table (fstab).
:enable
Add an entry to the file systems table (fstab).
:mount
Default. Mount a device.
: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.
:remount
Remount a device.
:umount
Unmount a device.
:unmount
Alias for :umount action.

Note

Order matters when passing multiple actions. For example: action [:mount, :enable] ensures that the file system is mounted before it is enabled.

Properties

The mount resource has the following properties:

device

Ruby Type: String

Required for :umount and :remount actions (for the purpose of checking the mount command output for presence). The special block device or remote node, a label, or a uuid to be mounted.

device_type

Ruby Type: String, Symbol | Default Value: device

The type of device: :device, :label, or :uuid

domain

Ruby Type: String

Windows only: Use to specify the domain in which the username and password are located.

dump

Ruby Type: Integer, false | Default Value: 0

The dump frequency (in days) used while creating a file systems table (fstab) entry.

enabled

Ruby Type: true, false | Default Value: false

Use to specify if a mounted file system is enabled.

fsck_device

Ruby Type: String | Default Value: -

Solaris only: The fsck device.

fstype

Ruby Type: String, nil | Default Value: auto

Required. The file system type (fstype) of the device.

ignore_failure

Ruby Type: true, false | Default Value: false

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

mount_point

Ruby Type: String

The directory (or path) in which the device is to be mounted. Default value: the name of the resource block. See “Syntax” section above for more information.

mounted

Ruby Type: true, false | Default Value: false

Use to specify if a file system is already mounted.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: Array, String | Default Value: defaults

An array or string that contains mount options. If this value is a string, it is converted to an array.

pass

Ruby Type: Integer, false | Default Value: 2

The pass number used by the file system check (fsck) command while creating a file systems table (fstab) entry.

password

Ruby Type: String

Microsoft Windows only. Use to specify the password for username.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Hash, Array

Specify a Hash of supported mount features. Default value: remount: false (preferred). Array defaults to remount: true (non-preferred).

username

Ruby Type: String

Microsoft Windows only. Use to specify the user name.

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.

Mount a labeled file system

mount '/mnt/volume1' do
  device 'volume1'
  device_type :label
  fstype 'xfs'
  options 'rw'
end

Mount a local block drive

mount '/mnt/local' do
  device '/dev/sdb1'
  fstype 'ext3'
end

Mount a non-block file system

mount '/mount/tmp' do
  pass     0
  fstype   'tmpfs'
  device   '/dev/null'
  options  'nr_inodes=999k,mode=755,size=500m'
  action   [:mount, :enable]
end

Mount and add to the file systems table

mount '/export/www' do
  device 'nas1prod:/export/web_sites'
  fstype 'nfs'
  options 'rw'
  action [:mount, :enable]
end

Mount a remote file system

mount '/export/www' do
  device 'nas1prod:/export/web_sites'
  fstype 'nfs'
  options 'rw'
end

Mount a remote folder in Microsoft Windows

mount 'T:' do
  action :mount
  device '\\\\hostname.example.com\\folder'
end

Unmount a remote folder in Microsoft Windows

mount 'T:' do
  action :umount
  device '\\\\hostname.example.com\\D$'
end

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

msu_package resource

[edit on GitHub]

Use the msu_package resource to install Microsoft Update(MSU) packages on Microsoft Windows machines.

New in Chef Client 12.17.

Syntax

The msu_package resource has the following syntax:

msu_package 'name' do
  source                     String
  action                     Symbol
end

where:

  • msu_package is the resource.
  • name is the name given to the resource block.
  • source is the local path or URL for the MSU package.

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

msu_package 'name' do
   source                    String
   checksum                  String
   action                    Symbol
end

Actions

The msu_package resource has the following actions:

:install
Installs the MSU package from either a local file path or URL.
:remove
Uninstalls the MSU package from its location on disk.

Properties

The msu_package resource has the following properties:

checksum

Ruby Type: String

SHA-256 digest used to verify the checksum of the downloaded MSU package.

source

Ruby Type: String

The local file path or URL for the MSU package.

Examples

Using local path in source

msu_package 'Install Windows 2012R2 Update KB2959977' do
  source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu'
  action :install
end
msu_package 'Remove Windows 2012R2 Update KB2959977' do
  source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu'
  action :remove
end

Using URL in source

msu_package 'Install Windows 2012R2 Update KB2959977' do
  source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu'
  action :install
end
msu_package 'Remove Windows 2012R2 Update KB2959977' do
  source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu'
  action :remove
end

ohai resource

[edit on GitHub]

Use the ohai resource to reload the Ohai configuration on a node. This allows recipes that change system attributes (like a recipe that adds a user) to refer to those attributes later on during the chef-client run.

Syntax

The ohai resource has the following syntax:

ohai 'name' do
  ohai_name       # default value: 'name' unless specified
  plugin         String
  action         Symbol # defaults to :reload if not specified
end

where:

  • ohai is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • ohai_name and plugin are the properties available to this resource.

Actions

The ohai 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.
:reload
Default. Reload the Ohai configuration on a node.

Properties

The ohai resource has the following properties:

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The name of an Ohai plugin to be reloaded. If this property is not specified, the chef-client will reload all plugins.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

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.

Reload Ohai

ohai 'reload' do
  action :reload
end

Reload Ohai after a new user is created

ohai 'reload_passwd' do
  action :nothing
  plugin 'etc'
end

user 'daemonuser' do
  home '/dev/null'
  shell '/sbin/nologin'
  system true
  notifies :reload, 'ohai[reload_passwd]', :immediately
end

ruby_block 'just an example' do
  block do
    # These variables will now have the new values
    puts node['etc']['passwd']['daemonuser']['uid']
    puts node['etc']['passwd']['daemonuser']['gid']
  end
end

ohai_hint resource

[edit on GitHub]

Use the ohai_hint resource to aid in configuration detection by passing hint data to Ohai.

New in Chef Client 14.0.

Syntax

The ohai_hint resource has the following syntax:

ohai_hint 'name' do
  compile_time      true, false # default value: true
  content           Hash
  hint_name         String # default value: 'name' unless specified
  action            Symbol # defaults to :create if not specified
end

where:

  • ohai_hint is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • compile_time, content, and hint_name are the properties available to this resource.

Actions

The ohai_hint resource has the following actions:

:create
Default. Create an Ohai hint file.
:delete
Delete an Ohai hint file.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, the resource block is either run immediately or it is queued up to be run at the end of the Chef Client run.

Properties

The ohai_hint resource has the following properties:

compile_time

Ruby Type: true, false | Default Value: true

Determines whether or not the resource is executed during the compile time phase.

content

Ruby Type: Hash

Values to include in the hint file.

hint_name

Ruby Type: String | Default Value: 'name'

The name of the hints file, if it differs from the resource name.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Examples

Create a hint file

ohai_hint 'example' do
  content Hash[:a, 'test_content']
end

Create a hint file with a name that does not match the resource name

ohai_hint 'example' do
  hint_name 'custom'
end

Create a hint file that is not loaded at compile time

ohai_hint 'example' do
  compile_time false
end

Delete a hint file

ohai-hint 'example' do
  action :delete
end

openbsd_package resource

[edit on GitHub]

Use the openbsd_package resource to manage packages for the OpenBSD 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 openbsd_package resource block manages a package on a node, typically by installing it. The simplest use of the openbsd_package resource is:

openbsd_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 openbsd_package resource is:

openbsd_package 'name' do
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where

  • openbsd_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, 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

The openbsd_package 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 Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

openbsd_package 'name of package' do
  action :install
end

openssl_dhparam resource

[edit on GitHub]

Use the openssl_dhparam resource to generate dhparam.pem files. If a valid dhparam.pem file is found at the specified location, no new file will be created. If a file is found at the specified location, but it is not a valid dhparam file, it will be overwritten.

New in Chef Client 14.0.

Syntax

The openssl_dhparam resource has the following syntax:

openssl_dhparam 'name' do
  generator       Integer # default value: 2
  group           String
  key_length      Integer # default value: 2048
  mode            Integer, String # default value: 0640
  owner           String
  path            String # default value: 'name' unless specified
  action          Symbol # defaults to :create if not specified
end

where:

  • openssl_dhparam is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • generator, group, key_length, mode, owner, and path are the properties available to this resource.

Actions

The openssl_dhparam resource has the following actions:

:create
Default. Create the dhparam.pem 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.

Properties

The openssl_dhparam resource has the following properties:

generator

Ruby Type: Integer | Default Value: 2

The desired Diffie-Hellmann generator; available options are 2 and 5.

group

Ruby Type: String

The group ownership applied to all files created by the resource.

key_length

Ruby Type: Integer | Default Value: 2048

The desired bit length of the generated key; available options are 1024, 2048, 4096, and 8192.

mode

Ruby Type: Integer, String | Default Value: 0640

The permission mode applied to all files created by the resource.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The owner applied to all files created by the resource.

path

Ruby Type: String

The path to write the file to, if it differs from the resource name.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Examples

Create a dhparam file

openssl_dhparam '/etc/httpd/ssl/dhparam.pem'

Create a dhparam file with a specific key length

openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do
  key_length 4096
end

Create a dhparam file with specific user/group ownership

openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do
  owner 'www-data'
  group 'www-data'
end

Manually specify the dhparam file path

openssl_dhparam 'httpd_dhparam' do
  path '/etc/httpd/ssl/dhparam.pem'
end

openssl_ec_public_key resource

[edit on GitHub]

Use the openssl_ec_public_key resource to generate elliptic curve (EC) public key files from a given EC private key.

New in Chef Client 14.4.

Syntax

The openssl_ec_public_key resource has the following syntax:

openssl_ec_public_key 'name' do
  group                    String
  mode                     Integer, String # default value: 0640
  owner                    String
  path                     String # default value: 'name' unless specified
  private_key_content      String
  private_key_pass         String
  private_key_path         String
  action                   Symbol # defaults to :create if not specified
end

where:

  • openssl_ec_public_key is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • group, mode, owner, path, private_key_content, private_key_pass, and private_key_path are the properties available to this resource.

Actions

The openssl_ec_public_key resource has the following actions:

:create
Default. Generate the EC public key from a private key.
: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

The openssl_ec_public_key resource has the following properties:

group

Ruby Type: String

The group ownership applied to all files created by the resource.

mode

Ruby Type: Integer, String | Default Value: 0640

The permission mode applied to all files created by the resource.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The owner applied to all files created by the resource.

path

Ruby Type: String

The path of the public key file, if it differs from the resource name.

private_key_content

Ruby Type: String

The content of the private key, including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk.

private_key_pass

Ruby Type: String

The passphrase of the provided private key.

private_key_path

Ruby Type: String

The path to the private key file.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Examples

Create a public key from a private key file

openssl_ec_public_key '/etc/example/key.pub' do
  private_key_path '/etc/example/key.pem'
end

Create a public key from a private key, without writing the private key to disk

You can provide the private key content as a string to the openssl_ec_public_key resource. In this example we just pass a string, but this content could be loaded from an encrypted data bag or other secure storage.

openssl_ec_public_key '/etc/example/key.pub' do
  private_key_content 'KEY_CONTENT_HERE_AS_A_STRING'
end

openssl_ec_private_key resource

[edit on GitHub]

Use the openssl_ec_private_key resource to generate an elliptic curve (EC) private key file. If a valid EC key file can be opened at the specified location, no new file will be created. If the EC key file cannot be opened – either because it does not exist or because the password to the EC key file does not match the password in the recipe – then it will be overwritten.

New in Chef Client 14.4.

Syntax

The openssl_ec_private_key resource has the following syntax:

openssl_ec_private_key 'name' do
  force           true, false # default value: false
  group           String
  key_cipher      String # default value: des3
  key_curve       String # default value: prime256v1
  key_pass        String
  mode            Integer, String # default value: 0600
  owner           String
  path            String # default value: 'name' unless specified
  action          Symbol # defaults to :create if not specified
end

where:

  • openssl_ec_private_key is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • force, group, key_cipher, key_curve, key_pass, mode, owner, and path are the properties available to this resource.

Actions

The openssl_ec_private_key resource has the following actions:

:create
Default. Create the EC private key 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.

Properties

The openssl_ec_private_key resource has the following properties:

force

Ruby Type: true, false | Default Value: false

Force creation of the key even if the same key already exists on the node.

group

Ruby Type: String

The group ownership applied to all files created by the resource.

key_cipher

Ruby Type: String | Default Value: des3

The designed cipher to use when generating your key. Run openssl list-cipher-algorithms to see available options.

key_curve

Ruby Type: String | Default Value: prime256v1

The desired curve of the generated key (if key_type is equal to ‘ec’). Run openssl ecparam -list_curves to see available options.

key_pass

Ruby Type: String

The desired passphrase for the key.

mode

Ruby Type: Integer, String | Default Value: 0600

The permission mode applied to all files created by the resource.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The owner applied to all files created by the resource.

path

Ruby Type: String

The path where the private key file will be created, if it differs from the resource name.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

openssl_rsa_public_key resource

[edit on GitHub]

Use the openssl_rsa_public_key resource to generate RSA public key files for a given RSA private key.

New in Chef Client 14.0.

Syntax

The openssl_rsa_public_key resource has the following syntax:

openssl_rsa_public_key 'name' do
  group                    String
  mode                     Integer, String # default value: 0640
  owner                    String
  path                     String # default value: 'name' unless specified
  private_key_content      String
  private_key_pass         String
  private_key_path         String
  action                   Symbol # defaults to :create if not specified
end

where:

  • openssl_rsa_public_key is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • group, mode, owner, path, private_key_content, private_key_pass, and private_key_path are the properties available to this resource.

Actions

The openssl_rsa_public_key resource has the following actions:

:create
Default. Create the RSA public key.
: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

The openssl_rsa_public_key resource has the following properties:

group

Ruby Type: String

The group ownership applied to all files created by the resource.

mode

Ruby Type: Integer, String | Default Value: 0640

The permission mode applied to all files created by the resource.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The owner applied to all files created by the resource.

path

Ruby Type: String

The path to the public key file, if it differs from the resource name.

private_key_content

Ruby Type: String

The content of the private key, including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk.

private_key_pass

Ruby Type: String

The passphrase of the provided private key.

private_key_path

Ruby Type: String

The path to the private key file.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Examples

Create a public key from a private key file

openssl_rsa_public_key '/etc/example/key.pub' do
  private_key_path '/etc/example/key.pem'
end

Create a public key from a private key, without writing the private key to disk

You can provide the private key content as a string to the openssl_rsa_public_key resource. In this example we just pass a string, but this content could be loaded from an encrypted data bag or other secure storage.

openssl_rsa_public_key '/etc/example/key.pub' do
  private_key_content 'KEY_CONTENT_HERE_AS_A_STRING'
end

openssl_rsa_private_key resource

[edit on GitHub]

Use the openssl_rsa_private_key resource to generate RSA private key files. If a valid RSA key file can be opened at the specified location, no new file will be created. If the RSA key file cannot be opened or does not exist, it will be overwritten.

Note

If the password to your RSA key file does not match the password in the recipe, it cannot be opened, and will be overwritten.

New in Chef Client 14.0.

Syntax

The openssl_rsa_private_key resource has the following syntax:

openssl_rsa_private_key 'name' do
  force           true, false # default value: false
  group           String
  key_cipher      String # default value: des3
  key_length      Integer # default value: 2048
  key_pass        String
  mode            Integer, String # default value: 0600
  owner           String
  path            String # default value: 'name' unless specified
  action          Symbol # defaults to :create if not specified
end

where:

  • openssl_rsa_private_key is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • force, group, key_cipher, key_length, key_pass, mode, owner, and path are the properties available to this resource.

Actions

The openssl_rsa_private_key resource has the following actions:

:create
Default. Create the RSA private key 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.

Properties

The openssl_rsa_private_key resource has the following properties:

force

Ruby Type: true, false | Default Value: false

Force creation of the key even if the same key already exists on the node.

group

Ruby Type: String

The group ownership applied to all files created by the resource.

key_cipher

Ruby Type: String | Default Value: des3

The designed cipher to use when generating your key. Run openssl list-cipher-algorithms to see available options.

key_length

Ruby Type: Integer | Default Value: 2048

The desired bit length of the generated key; available options are 1024, 2048, 4096, and 8192.

key_pass

Ruby Type: String

The desired passphrase for the key.

mode

Ruby Type: Integer, String | Default Value: 0600

The permission mode applied to all files created by the resource.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The owner applied to all files created by the resource.

path

Ruby Type: String

The path where the private key file will be created, if it differs from the resource name.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

openssl_x509_certificate resource

[edit on GitHub]

Use the openssl_x509_certificate resource to generate signed or self-signed, PEM-formatted x509 certificates. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate. If a CA private key and certificate are provided, the certificate will be signed with them. Note: This resource was renamed from openssl_x509 to openssl_x509_certificate. The legacy name will continue to function, but cookbook code should be updated for the new resource name.

New in Chef Client 14.4.

Syntax

The openssl_x509_certificate resource has the following syntax:

openssl_x509_certificate 'name' do
  ca_cert_file          String
  ca_key_file           String
  ca_key_pass           String
  city                  String
  common_name           String
  country               String
  csr_file              String
  email                 String
  expire                Integer # default value: 365
  extensions            Hash
  group                 String
  key_curve             String # default value: prime256v1
  key_file              String
  key_length            Integer # default value: 2048
  key_pass              String
  key_type              String # default value: rsa
  mode                  Integer, String
  org                   String
  org_unit              String
  owner                 String
  path                  String # default value: 'name' unless specified
  state                 String
  subject_alt_name      Array
  action                Symbol # defaults to :create if not specified
end

where:

  • openssl_x509_certificate is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • ca_cert_file, ca_key_file, ca_key_pass, city, common_name, country, csr_file, email, expire, extensions, group, key_curve, key_file, key_length, key_pass, key_type, mode, org, org_unit, owner, path, state, and subject_alt_name are the properties available to this resource.

Actions

The openssl_x509_certificate resource has the following actions:

:create
Default. Create the certificate 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.

Properties

city

Ruby Type: String

Value for the L certificate field.

email

Ruby Type: String

Value for the email ssl field.

ca_cert_file

Ruby Type: String

The path to the CA X509 Certificate on the filesystem. If the ca_cert_file property is specified, the ca_key_file property must also be specified, the certificate will be signed with them.

ca_key_file

Ruby Type: String

The path to the CA private key on the filesystem. If the ca_key_file property is specified, the ca_cert_file property must also be specified, the certificate will be signed with them.

ca_key_pass

Ruby Type: String

The passphrase for CA private key’s passphrase.

city

Ruby Type: String

Value for the L certificate field.

common_name

Ruby Type: String

Value for the CN certificate field.

country

Ruby Type: String

Value for the C certificate field.

csr_file

Ruby Type: String

The path to a X509 Certificate Request (CSR) on the filesystem. If the csr_file property is specified, the resource will attempt to source a CSR from this location. If no CSR file is found, the resource will generate a Self-Signed Certificate and the certificate fields must be specified (common_name at last).

email

Ruby Type: String

Value for the email certificate field.

expire

Ruby Type: Integer | Default Value: 365

Value representing the number of days from now through which the issued certificate cert will remain valid. The certificate will expire after this period.

extensions

Ruby Type: Hash

Hash of X509 Extensions entries, in format { 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true } }.

group

Ruby Type: String

The group ownership applied to all files created by the resource.

key_curve

Ruby Type: String | Default Value: prime256v1

The desired curve of the generated key (if key_type is equal to ‘ec’). Run openssl ecparam -list_curves to see available options.

key_file

Ruby Type: String

The path to a certificate key file on the filesystem. If the key_file property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the key_file property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate.

key_length

Ruby Type: Integer | Default Value: 2048

The desired bit length of the generated key (if key_type is equal to ‘rsa’). Available options are 1024, 2048, 4096, and 8192.

key_pass

Ruby Type: String

The passphrase for an existing key’s passphrase.

key_type

Ruby Type: String | Default Value: rsa

The desired type of the generated key (rsa or ec).

mode

Ruby Type: Integer, String

The permission mode applied to all files created by the resource.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

Value for the O certificate field.

org_unit

Ruby Type: String

Value for the OU certificate field.

owner

Ruby Type: String

The owner applied to all files created by the resource.

path

Ruby Type: String

The path to write the file to, if it differs from the resource name.

state

Ruby Type: String

Value for the ST certificate field.

subject_alt_name

Ruby Type: Array

Array of Subject Alternative Name entries, in format DNS:example.com or IP:1.2.3.4.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Examples

Create a simple self-signed certificate file

openssl_x509 '/etc/httpd/ssl/mycert.pem' do
  common_name 'www.f00bar.com'
  org 'Foo Bar'
  org_unit 'Lab'
  country 'US'
end

Create a certificate using additional options

  openssl_x509_certificate '/etc/ssl_test/my_signed_cert.crt' do
  common_name 'www.f00bar.com'
  ca_key_file '/etc/ssl_test/my_ca.key'
  ca_cert_file '/etc/ssl_test/my_ca.crt'
  expire 365
  extensions(
    'keyUsage' => {
      'values' => %w(
        keyEncipherment
        digitalSignature),
      'critical' => true,
    },
    'extendedKeyUsage' => {
      'values' => %w(serverAuth),
      'critical' => false,
    }
  )
  subject_alt_name ['IP:127.0.0.1', 'DNS:localhost.localdomain']
end

openssl_x509_crl resource

[edit on GitHub]

Use the openssl_x509_crl resource to generate PEM-formatted x509 certificate revocation list (CRL) files.

New in Chef Client 14.4.

Syntax

The openssl_x509_crl resource has the following syntax:

openssl_x509_crl 'name' do
  ca_cert_file           String
  ca_key_file            String
  ca_key_pass            String
  expire                 Integer # default value: 8
  group                  String
  mode                   Integer, String
  owner                  String
  path                   String # default value: 'name' unless specified
  renewal_threshold      Integer # default value: 1
  revocation_reason      Integer # default value: 0
  serial_to_revoke       Integer, String
  action                 Symbol # defaults to :create if not specified
end

where:

  • openssl_x509_crl is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • ca_cert_file, ca_key_file, ca_key_pass, expire, group, mode, owner, path, renewal_threshold, revocation_reason, and serial_to_revoke are the properties available to this resource.

Actions

The openssl_x509_crl resource has the following actions:

:create
Default. Create the certificate revocation list 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.

Properties

ca_cert_file

Ruby Type: String

The path to the CA X509 Certificate on the filesystem. If the ca_cert_file property is specified, the ca_key_file property must also be specified, the CRL will be signed with them.

ca_key_file

Ruby Type: String

The path to the CA private key on the filesystem. If the ca_key_file property is specified, the ca_cert_file property must also be specified, the CRL will be signed with them.

ca_key_pass

Ruby Type: String

The passphrase for CA private key’s passphrase.

expire

Ruby Type: Integer | Default Value: 8

Value representing the number of days from now through which the issued CRL will remain valid. The CRL will expire after this period.

group

Ruby Type: String

The group permission for the CRL file.

mode

Ruby Type: Integer, String

The permission mode of the CRL file.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

The owner permission for the CRL file.

path

Ruby Type: String

The path to write the file to, if it differs from the resource name.

renewal_threshold

Ruby Type: Integer | Default Value: 1

Number of days before the expiration. It this threshold is reached, the CRL will be renewed.

revocation_reason

Ruby Type: Integer | Default Value: 0

Reason for the revocation.

serial_to_revoke

Ruby Type: Integer, String

Serial of the X509 Certificate to revoke.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Examples

Create a certificate revocation file

openssl_x509_crl '/etc/ssl_test/my_ca.crl' do
  ca_cert_file '/etc/ssl_test/my_ca.crt'
  ca_key_file '/etc/ssl_test/my_ca.key'
end

Create a certificate revocation file for a particular serial

openssl_x509_crl '/etc/ssl_test/my_ca.crl' do
  ca_cert_file '/etc/ssl_test/my_ca.crt'
  ca_key_file '/etc/ssl_test/my_ca.key'
  serial_to_revoke C7BCB6602A2E4251EF4E2827A228CB52BC0CEA2F
end

openssl_x509_request resource

[edit on GitHub]

Use the openssl_x509_request resource to generate PEM-formatted x509 certificates requests. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate.

New in Chef Client 14.4.

Syntax

The openssl_x509_request resource has the following syntax:

openssl_x509_request 'name' do
  city             String
  common_name      String
  country          String
  email            String
  group            String
  key_curve        String # default value: prime256v1
  key_file         String
  key_length       Integer # default value: 2048
  key_pass         String
  key_type         String # default value: ec
  mode             Integer, String
  org              String
  org_unit         String
  owner            String
  path             String # default value: 'name' unless specified
  state            String
  action           Symbol # defaults to :create if not specified
end

where:

  • openssl_x509_request is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • city, common_name, country, email, group, key_curve, key_file, key_length, key_pass, key_type, mode, org, org_unit, owner, path, and state are the properties available to this resource.

Actions

The openssl_x509_request resource has the following actions:

:create
Default. Create the certificate request 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.

Properties

city

Ruby Type: String

Value for the L certificate field.

common_name

Ruby Type: String

Value for the CN certificate field.

country

Ruby Type: String

Value for the C certificate field.

email

Ruby Type: String

Value for the email certificate field.

group

Ruby Type: String

The group ownership applied to all files created by the resource.

key_curve

Ruby Type: String | Default Value: prime256v1

The desired curve of the generated key (if key_type is equal to ‘ec’). Run openssl ecparam -list_curves to see available options.

key_file

Ruby Type: String

The path to a certificate key file on the filesystem. If the key_file property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the key_file property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate.

key_length

Ruby Type: Integer | Default Value: 2048

The desired bit length of the generated key (if key_type is equal to ‘rsa’). Available options are 1024, 2048, 4096, and 8192.

key_pass

Ruby Type: String

The passphrase for an existing key’s passphrase.

key_type

Ruby Type: String | Default Value: ec

The desired type of the generated key (rsa or ec).

mode

Ruby Type: Integer, String

The permission mode applied to all files created by the resource.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

Value for the O certificate field.

org_unit

Ruby Type: String

Value for the OU certificate field.

owner

Ruby Type: String

The owner applied to all files created by the resource.

path

Ruby Type: String

The path to write the file to, if it differs from the resource name.

state

Ruby Type: String

Value for the ST certificate field.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Examples

Create a certificate request file

openssl_x509_request '/etc/ssl_test/my_ec_request.csr' do
  common_name 'myecrequest.example.com'
  org 'Test Kitchen Example'
  org_unit 'Kitchens'
  country 'UK'
end

osx_profile resource

[edit on GitHub]

Use the osx_profile resource to manage configuration profiles (.mobileconfig files) on the macOS platform. The osx_profile resource installs profiles by using the uuidgen library to generate a unique ProfileUUID, and then using the profiles command to install the profile on the system.

Syntax

The osx_profile resource has the following syntax:

osx_profile 'name' do
  identifier        String
  path              String
  profile           String, Hash
  profile_name      String # default value: 'name' unless specified
  action            Symbol # defaults to :install if not specified
end

where:

  • osx_profile is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • identifier, path, profile, and profile_name are the properties available to this resource.

Actions

The osx_profile resource has the following actions:

:install
Default. Install the specified configuration profile.
:nothing

Default. .. tag resources_common_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.
:remove
Remove the specified configuration profile.

Properties

The osx_profile resource has the following properties:

identifier

Ruby Type: String

Use to specify the identifier for the profile, such as com.company.screensaver.

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String, Hash

Use to specify a profile. This may be the name of a profile contained in a cookbook or a Hash that contains the contents of the profile.

profile_name

Ruby Type: String

Use to specify the name of the profile, if different from the name of the resource block.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

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.

One liner to install profile from cookbook file

The profiles command will be used to install the specified configuration profile.

osx_profile 'com.company.screensaver.mobileconfig'

Install profile from cookbook file

The profiles command will be used to install the specified configuration profile. It can be in sub-directory within a cookbook.

osx_profile 'Install screensaver profile' do
  profile 'screensaver/com.company.screensaver.mobileconfig'
end

Install profile from a hash

The profiles command will be used to install the configuration profile, which is provided as a hash.

profile_hash = {
  'PayloadIdentifier' => 'com.company.screensaver',
  'PayloadRemovalDisallowed' => false,
  'PayloadScope' => 'System',
  'PayloadType' => 'Configuration',
  'PayloadUUID' => '1781fbec-3325-565f-9022-8aa28135c3cc',
  'PayloadOrganization' => 'Chef',
  'PayloadVersion' => 1,
  'PayloadDisplayName' => 'Screensaver Settings',
  'PayloadContent'=> [
    {
      'PayloadType' => 'com.apple.ManagedClient.preferences',
      'PayloadVersion' => 1,
      'PayloadIdentifier' => 'com.company.screensaver',
      'PayloadUUID' => '73fc30e0-1e57-0131-c32d-000c2944c108',
      'PayloadEnabled' => true,
      'PayloadDisplayName' => 'com.apple.screensaver',
      'PayloadContent' => {
        'com.apple.screensaver' => {
          'Forced' => [
            {
              'mcx_preference_settings' => {
                'idleTime' => 0,
              }
            }
          ]
        }
      }
    }
  ]
}

osx_profile 'Install screensaver profile' do
  profile profile_hash
end

Remove profile using identifier in resource name

The profiles command will be used to remove the configuration profile specified by the provided identifier property.

osx_profile 'com.company.screensaver' do
  action :remove
end

Remove profile by identifier and user friendly resource name

The profiles command will be used to remove the configuration profile specified by the provided identifier property.

osx_profile 'Remove screensaver profile' do
  identifier 'com.company.screensaver'
  action :remove
end

package resource

[edit on GitHub]

Use the package resource to manage packages. When the package is installed from a local file (such as with RubyGems, dpkg, or RPM Package Manager), the file must be added to the node using the remote_file or cookbook_file resources.

This resource is the base resource for several other resources used for package management on specific platforms. While it is possible to use each of these specific resources, it is recommended to use the package resource as often as possible.

For more information about specific resources for specific platforms, see the following topics:

Syntax

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

package 'httpd'

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

For a package that has different package names, depending on the platform, use a case statement within the package:

package 'Install Apache' do
  case node[:platform]
  when 'redhat', 'centos'
    package_name 'httpd'
  when 'ubuntu', 'debian'
    package_name 'apache2'
  end
end

where 'redhat', 'centos' will install Apache using the httpd package and 'ubuntu', 'debian' will install it using the apache2 package

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

package 'name' do
  allow_downgrade            true, false # Yum, RPM packages only
  arch                       String, Array # Yum packages only
  default_release            String # Apt packages only
  flush_cache                Array
  gem_binary                 String
  homebrew_user              String, Integer # Homebrew packages only
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  response_file              String # Apt packages only
  response_file_variables    Hash # Apt packages only
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • package tells the chef-client to manage a package; the chef-client will determine the correct package provider to use based on the platform running on the node
  • 'name' is the name of the package
  • action identifies which steps the chef-client will take to bring the node into the desired state
  • allow_downgrade, arch, default_release, flush_cache, gem_binary, homebrew_user, options, package_name, response_file, response_file_variables, source, recursive, 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 Chef 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.

Warning

Gem package options should only be used when gems are installed into the system-wide instance of Ruby, and not the instance of Ruby dedicated to the chef-client.

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. (Debian platform only; for other platforms, use the :remove action.)
: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 attributes:

allow_downgrade

Ruby Type: true, false | Default Value: false

yum_package resource only. Downgrade a package to satisfy requested version requirements.

arch

Ruby Type: String, Array

yum_package resource only. The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name.

default_release

Ruby Type: String

apt_package resource only. The default release. For example: stable.

flush_cache

Ruby Type: Array

Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Default value: [ :before, :after ]. The value may also be a Hash: ( { :before => true/false, :after => true/false } ).

Yum automatically synchronizes remote metadata to a local cache. The chef-client creates a copy of the local cache, and then stores it in-memory during the chef-client run. The in-memory cache allows packages to be installed during the chef-client run without the need to continue synchronizing the remote metadata to the local cache while the chef-client run is in-progress.

As an array:

yum_package 'some-package' do
  #...
  flush_cache [ :before ]
  #...
end

and as a Hash:

yum_package 'some-package' do
  #...
  flush_cache( { :after => true } )
  #...
end

Note

The flush_cache property does not flush the local Yum cache! Use Yum tools—yum clean headers, yum clean packages, yum clean all—to clean the local Yum cache.

gem_binary

Ruby Type: String

A property for the gem_package provider that is used to specify a gems binary.

homebrew_user

Ruby Type: String, Integer

homebrew_package resource only. The name of the Homebrew owner to be used by the chef-client when executing a command.

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

response_file

Ruby Type: String

apt_package and dpkg_package resources only. The direct path to the file used to pre-seed a package.

response_file_variables

Ruby Type: Hash

apt_package and dpkg_package resources only. A Hash of response file variables in the form of {"VARIABLE" => "VALUE"}.

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source

Ruby Type: String

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

Note

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: 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, DNF, 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 %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(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.

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 gems file for use in recipes

chef_gem 'right_aws' do
  action :install
end

require 'right_aws'

Install a gems file from the local file system

gem_package 'right_aws' do
  source '/tmp/right_aws-1.11.0.gem'
  action :install
end

Install a package

package 'tar' do
  action :install
end

Install a package version

package 'tar' do
  version '1.16.1-1'
  action :install
end

Install a package with options

package 'debian-archive-keyring' do
  action :install
  options '--force-yes'
end

Install a package with a response_file

Use of a response_file is only supported on Debian and Ubuntu at this time. Custom resources must be written to support the use of a response_file, which contains debconf answers to questions normally asked by the package manager on installation. Put the file in /files/default of the cookbook where the package is specified and the chef-client will use the cookbook_file resource to retrieve it.

To install a package with a response_file:

package 'sun-java6-jdk' do
  response_file 'java.seed'
end

Install a specified architecture using a named provider

yum_package 'glibc-devel' do
  arch 'i386'
end

Purge a package

package 'tar' do
  action :purge
end

Remove a package

package 'tar' do
  action :remove
end

Upgrade a package

package 'tar' do
  action :upgrade
end

Use the ignore_failure common attribute

gem_package 'syntax' do
  action :install
  ignore_failure true
end

Avoid unnecessary string interpolation

Do this:

package 'mysql-server' do
  version node['mysql']['version']
  action :install
end

and not this:

package 'mysql-server' do
  version "#{node['mysql']['version']}"
  action :install
end

Install a package in a platform

The following example shows how to use the package resource to install an application named app and ensure that the correct packages are installed for the correct platform:

package 'app_name' do
  action :install
end

case node[:platform]
when 'ubuntu','debian'
  package 'app_name-doc' do
    action :install
  end
when 'centos'
  package 'app_name-html' do
    action :install
  end
end

Install sudo, then configure /etc/sudoers/ file

The following example shows how to install sudo and then configure the /etc/sudoers file:

#  the following code sample comes from the ``default`` recipe in the ``sudo`` cookbook: https://github.com/chef-cookbooks/sudo

package 'sudo' do
  action :install
end

if node['authorization']['sudo']['include_sudoers_d']
  directory '/etc/sudoers.d' do
    mode        '0755'
    owner       'root'
    group       'root'
    action      :create
  end

  cookbook_file '/etc/sudoers.d/README' do
    source      'README'
    mode        '0440'
    owner       'root'
    group       'root'
    action      :create
  end
end

template '/etc/sudoers' do
  source 'sudoers.erb'
  mode '0440'
  owner 'root'
  group platform?('freebsd') ? 'wheel' : 'root'
  variables(
    :sudoers_groups => node['authorization']['sudo']['groups'],
    :sudoers_users => node['authorization']['sudo']['users'],
    :passwordless => node['authorization']['sudo']['passwordless']
  )
end

where

  • the package resource is used to install sudo
  • the if statement is used to ensure availability of the /etc/sudoers.d directory
  • the template resource tells the chef-client where to find the sudoers template
  • the variables property is a hash that passes values to template files (that are located in the templates/ directory for the cookbook

Use a case statement to specify the platform

The following example shows how to use a case statement to tell the chef-client which platforms and packages to install using cURL.

package 'curl'
  case node[:platform]
  when 'redhat', 'centos'
    package 'package_1'
    package 'package_2'
    package 'package_3'
  when 'ubuntu', 'debian'
    package 'package_a'
    package 'package_b'
    package 'package_c'
  end
end

where node[:platform] for each node is identified by Ohai during every chef-client run. For example:

package 'curl'
  case node[:platform]
  when 'redhat', 'centos'
    package 'zlib-devel'
    package 'openssl-devel'
    package 'libc6-dev'
  when 'ubuntu', 'debian'
    package 'openssl'
    package 'pkg-config'
    package 'subversion'
  end
end

Use symbols to reference attributes

Symbols may be used to reference attributes:

package 'mysql-server' do
  version node[:mysql][:version]
  action :install
end

instead of strings:

package 'mysql-server' do
  version node['mysql']['version']
  action :install
end

Use a whitespace array to simplify a recipe

The following examples show different ways of doing the same thing. The first shows a series of packages that will be upgraded:

package 'package-a' do
  action :upgrade
end

package 'package-b' do
  action :upgrade
end

package 'package-c' do
  action :upgrade
end

package 'package-d' do
  action :upgrade
end

and the next uses a single package resource and a whitespace array (%w):

package %w{package-a package-b package-c package-d} do
  action :upgrade
end

Specify the Homebrew user with a UUID

homebrew_package 'emacs' do
  homebrew_user 1001
end

Specify the Homebrew user with a string

homebrew_package 'vim' do
  homebrew_user 'user1'
end

pacman_package resource

[edit on GitHub]

Use the pacman_package resource to manage packages (using pacman) on the Arch Linux 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 pacman_package resource block manages a package on a node, typically by installing it. The simplest use of the pacman_package resource is:

pacman_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 pacman_package resource is:

pacman_package 'name' do
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • pacman_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • options, package_name, 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:

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

pacman_package 'name of package' do
  action :install
end

paludis_package resource

[edit on GitHub]

Use the paludis_package resource to manage packages for the Paludis 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 paludis_package resource block manages a package on a node, typically by installing it. The simplest use of the paludis_package resource is:

paludis_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 paludis_package resource is:

paludis_package 'name' do
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • paludis_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • options, package_name, source, recursive, 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.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties

This resource has the following properties:

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

paludis_package 'name of package' do
  action :install
end

perl resource

[edit on GitHub]

Use the perl resource to execute scripts using the Perl 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 perl 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 perl resource block executes scripts Perl:

perl 'hello world' do
  code <<-EOH
    print "Hello world! From Chef and Perl.";
    EOH
end

where

  • code specifies the command to run

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

perl 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  notifies                   # see description
  path                       Array
  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:

  • perl is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • code, creates, cwd, environment, flags, group, path, 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

The perl 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 Type: String, Integer

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

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
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:

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

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

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.

subscribes

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

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: Integer, Float | Default Value: 3600

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

user

Ruby Type: String, Integer

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

umask

Ruby Type: 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

Examples

None.

portage_package resource

[edit on GitHub]

Use the portage_package resource to manage packages for the Gentoo 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 portage_package resource block manages a package on a node, typically by installing it. The simplest use of the portage_package resource is:

portage_package 'package_name'

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

The portage_package resource has the following syntax:

portage_package 'name' do
  options                      String, Array
  package_name                 String, Array
  source                       String
  timeout                      String, Integer # default value: 3600
  version                      String, Array
  action                       Symbol # defaults to :install if not specified
end

where:

  • portage_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • options, package_name, source, timeout, and version are the properties available to this resource.

Actions

The portage_package 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:

ignore_failure

Ruby Type: true, false | Default Value: false

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

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

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

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

The syntax for notifies is:

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

Ruby Type: String

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

package_name

Ruby Type: String, Array

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

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

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

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

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

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

The syntax for subscribes is:

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

Ruby Type: String, Integer

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

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

portage_package 'name of package' do
  action :install
end

powershell_package resource

[edit on GitHub]

Use the powershell_package resource to install and manage packages via the PowerShell Package Manager for the Microsoft Windows platform. The powershell_package resource requires administrative access, and a source must be configured in the PowerShell Package Manager via the Register-PackageSource command or the powershell_package_source resource.

New in Chef Client 12.16.

Syntax

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

powershell_package 'package_name'

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

The powershell_package resource has the following syntax:

powershell_package 'name' do

  package_name               String, Array # defaults to 'name' if not specified
  version                    String, Array
  source                     String
  notifies                   # see description
  subscribes                 # see description
  action                     Symbol # defaults to :install if not specified
end

where:

  • powershell_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • package_name, version, source, notifies, and subscribes are properties of this resource, with the Ruby type shown. See the “Properties” section below for more information about all of the properties that may be used with this resource.

Actions

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

Properties

package_name

Ruby Type: String, Array

The name of the package. Default value: the name of the resource block.

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

source

Ruby Type: String

Specify the source of the package.

New in Chef Client 14.0.

notifies

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

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples

Install a specific version of a package:

powershell_package 'xCertificate' do
  action :install
  version '1.1.0.0'
end

Install multiple packages:

powershell_package 'Install Multiple Packages' do
  action :install
  package_name %w(xCertificate xNetworking)
end

Install a package from a custom source:

powershell_package 'xCertificate' do
  action :install
  source 'MyGallery'
end

Install multiple packages, and specify package versions:

powershell_package 'Install Multiple Packages' do
  action :install
  package_name %w(xCertificate xNetworking)
  version ['2.0.0.0', '2.12.0.0']
end

** Install multiple packages, specifying the package version for one package but not the other:**

powershell_package 'Install Multiple Packages' do
   action :install
   package_name %w(xCertificate xNetworking)
   version [nil, '2.12.0.0']
 end

In this example, the nil tells powershell_package to install the most up to date version of xCertificate that is available, while pinning xNetworking to version 2.12.0.0.

Remove a package:

powershell_package 'xCertificate' do
  action :remove
end

powershell_package_source resource

[edit on GitHub]

Use the powershell_package_source resource to register a PowerShell package repository.

New in Chef Client 14.3.

Syntax

The powershell_package_source resource has the following syntax:

powershell_package_source 'name' do
  provider_name                String # default value: NuGet
  publish_location             String
  script_publish_location      String
  script_source_location       String
  source_name                  String # default value: 'name' unless specified
  trusted                      true, false # default value: false
  url                          String
  action                       Symbol # defaults to :register if not specified
end

where:

  • powershell_package_source is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • provider_name, publish_location, script_publish_location, script_source_location, source_name, trusted, and url are the properties available to this resource.

Actions

register
Default. Registers and updates the PowerShell package source.
unregister
Unregisters the PowerShell package source.
: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

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
provider_name

Ruby Type: String | Default Value: NuGet

The package management provider for the source. It supports the following providers: ‘Programs’, ‘msi’, ‘NuGet’, ‘msu’, ‘PowerShellGet’, ‘psl’ and ‘chocolatey’.

publish_location

Ruby Type: String

The url where modules will be published to for this source. Only valid if the provider is ‘PowerShellGet’.

script_publish_location

Ruby Type: String

The location where scripts will be published to for this source. Only valid if the provider is ‘PowerShellGet’.

script_source_location

Ruby Type: String

The url where scripts are located for this source. Only valid if the provider is ‘PowerShellGet’.

source_name

Ruby Type: String

The name of the package source.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
trusted

Ruby Type: true, false | Default Value: false

Whether or not to trust packages from this source.

url

Ruby Type: String

The url to the package source.

powershell_script resource

[edit on GitHub]

Use the powershell_script resource to execute a script using the Windows PowerShell interpreter, much like how the script and script-based resources—bash, csh, perl, python, and ruby—are used. The powershell_script is specific to the Microsoft Windows platform and the Windows PowerShell interpreter.

The powershell_script resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. 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.

Changed in 12.19 to support windows alternate user identity in execute resources

Syntax

A powershell_script resource block executes a batch script using the Windows PowerShell interpreter. For example, writing to an interpolated path:

powershell_script 'write-to-interpolated-path' do
  code <<-EOH
  $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt"
  $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.")
  $stream.close()
  EOH
end

The full syntax for all of the properties that are available to the powershell_script resource is:

powershell_script 'name' do
  architecture               Symbol
  code                       String
  command                    String, Array
  convert_boolean_return     true, false
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  guard_interpreter          Symbol
  interpreter                String
  notifies                   # see description
  returns                    Integer, Array
  sensitive                  true, false
  subscribes                 # see description
  timeout                    Integer, Float
  user                       String
  password                   String
  domain                     String
  action                     Symbol # defaults to :run if not specified
  elevated                   true, false
end

where

  • powershell_script 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, convert_boolean_return, creates, cwd, environment, flags, group, guard_interpreter, interpreter, returns, sensitive, timeout, user, password, domain and elevated 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
Inherited from execute resource. 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 the script.

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 Type: 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.

convert_boolean_return

Ruby Type: true, false | Default Value: false

Return 0 if the last line of a command is evaluated to be true or to return 1 if the last line is evaluated to be false.

When the guard_interpreter common attribute is set to :powershell_script, a string command will be evaluated as if this value were set to true. This is because the behavior of this attribute is similar to the value of the "$?" expression common in UNIX interpreters. For example, this:

powershell_script 'make_safe_backup' do
  guard_interpreter :powershell_script
  code 'cp ~/data/nodes.json ~/data/nodes.bak'
  not_if 'test-path ~/data/nodes.bak'
end

is similar to:

bash 'make_safe_backup' do
  code 'cp ~/data/nodes.json ~/data/nodes.bak'
  not_if 'test -e ~/data/nodes.bak'
end
creates

Ruby Type: String

Inherited from execute resource. Prevent a command from creating a file when that file already exists.

cwd

Ruby Type: String

Inherited from execute resource. The current working directory from which a command is run.

environment

Ruby Type: Hash

Inherited from execute resource. 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

A string that is passed to the Windows PowerShell command. Default value (Windows PowerShell 3.0+): -NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Bypass, -InputFormat None.

group

Ruby Type: String, Integer

Inherited from execute resource. The group name or group ID that must be changed before running a command.

guard_interpreter

Ruby Type: Symbol | Default Value: :powershell_script

When this property is set to :powershell_script, the 64-bit version of the Windows PowerShell 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 Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

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 notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

Inherited from execute resource. 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.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by the chef-client.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: Integer, Float

Inherited from execute resource. The amount of time (in seconds) a command is to wait before timing out. Default value: 3600.

user

Ruby Type: String | Default Value: nil

The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. domain\user 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 Type: 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 Type: String

Windows only: The domain of the 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.

elevated

Ruby Type: true, false

Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) interactively blocking the process.

This will cause the process to be run under a batch login instead of an interactive login. The user running Chef needs the “Replace a process level token” and “Adjust Memory Quotas for a process” permissions. The user that is running the command needs the “Log on as a batch job” permission.

Because this requires a login, the user and password properties are required.

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 different 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.

Write to an interpolated path

powershell_script 'write-to-interpolated-path' do
  code <<-EOH
  $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt"
  $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.")
  $stream.close()
  EOH
end

Change the working directory

powershell_script 'cwd-then-write' do
  cwd Chef::Config[:file_cache_path]
  code <<-EOH
  $stream = [System.IO.StreamWriter] "C:/powershell-test2.txt"
  $pwd = pwd
  $stream.WriteLine("This is the contents of: $pwd")
  $dirs = dir
  foreach ($dir in $dirs) {
    $stream.WriteLine($dir.fullname)
  }
  $stream.close()
  EOH
end

Change the working directory in Microsoft Windows

powershell_script 'cwd-to-win-env-var' do
  cwd '%TEMP%'
  code <<-EOH
  $stream = [System.IO.StreamWriter] "./temp-write-from-chef.txt"
  $stream.WriteLine("chef on windows rox yo!")
  $stream.close()
  EOH
end

Pass an environment variable to a script

powershell_script 'read-env-var' do
  cwd Chef::Config[:file_cache_path]
  environment ({'foo' => 'BAZ'})
  code <<-EOH
  $stream = [System.IO.StreamWriter] "./test-read-env-var.txt"
  $stream.WriteLine("FOO is $env:foo")
  $stream.close()
  EOH
end

Evaluate for true and/or false

Use the convert_boolean_return attribute to raise an exception when certain conditions are met. For example, the following fragments will run successfully without error:

powershell_script 'false' do
  code '$false'
end

and:

powershell_script 'true' do
  code '$true'
end

whereas the following will raise an exception:

powershell_script 'false' do
  convert_boolean_return true
  code '$false'
end

Use the flags attribute

powershell_script 'Install IIS' do
  code <<-EOH
  Import-Module ServerManager
  Add-WindowsFeature Web-Server
  EOH
  flags '-NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Unrestricted, -InputFormat None, -File'
  guard_interpreter :powershell_script
  not_if '(Get-WindowsFeature -Name Web-Server).Installed'
end

Rename computer, join domain, reboot

The following example shows how to rename a computer, join a domain, and then reboot the computer:

reboot 'Restart Computer' do
  action :nothing
end

powershell_script 'Rename and Join Domain' do
  code <<-EOH
    ...your rename and domain join logic here...
  EOH
  not_if <<-EOH
    $ComputerSystem = gwmi win32_computersystem
    ($ComputerSystem.Name -like '#{node['some_attribute_that_has_the_new_name']}') -and
      $ComputerSystem.partofdomain)
  EOH
  notifies :reboot_now, 'reboot[Restart Computer]', :immediately
end

where:

  • The powershell_script resource block renames a computer, and then joins a domain
  • The reboot resource restarts the computer
  • The not_if guard prevents the Windows PowerShell script from running when the settings in the not_if guard match the desired state
  • The notifies statement tells the reboot resource block to run if the powershell_script block was executed during the chef-client run

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
powershell_script 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username"
 password "password"
end

# Passing username and domain
powershell_script '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
powershell_script '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
powershell_script 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username@domain-name"
 password "password"
end

# Work around User Access Control (UAC)
powershell_script 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username"
 password "password"
 elevated true
end

python resource

[edit on GitHub]

Use the python resource to execute scripts using the Python 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 python 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

The python resource has the following syntax:

python 'hello world' do
  code <<-EOH
    print "Hello world! From Chef and Python."
    EOH
end

where

  • code specifies the command to run

The full syntax for all of the properties that are available to the python resource is:

python 'name' do
  code             String
  command
  creates          String
  cwd              String
  default_env      true, false # default value: false
  domain           String
  elevated         true, false # default value: false
  environment      Hash
  flags            String
  group            String, Integer
  interpreter      String
  live_stream      true, false # default value: false
  password         String
  returns          Integer, Array # default value: 0
  sensitive        true, false
  timeout          Integer, Float
  umask            String, Integer
  user             String, Integer
  action           Symbol # defaults to :run if not specified
end

where:

  • python is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • code, command, creates, cwd, default_env, domain, elevated, environment, flags, group, interpreter, live_stream, password, returns, sensitive, timeout, umask, and user are the properties available to this resource.

Actions

The python 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

The python 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 Type: String, Integer

The group name or group ID that must be changed before running a command.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
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:

python 'mycommand' do
  environment 'PATH' => "/my/path/to/bin:#{ENV['PATH']}"
end
retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

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.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: Integer, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

user

Ruby Type: String, Integer

The user name or user ID that should be changed before running a command.

umask

Ruby Type: 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

Examples

None.

reboot resource

[edit on GitHub]

Use the reboot resource to reboot a node, a necessary step with some installations on certain platforms. This resource is supported for use on the Microsoft Windows, macOS, and Linux platforms.

Syntax

The reboot resource has the following syntax:

reboot 'name' do
  delay_mins      Integer # default value: 0
  reason          String # default value: Reboot by Chef
  action          Symbol # defaults to :nothing if not specified
end

where:

  • reboot is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • delay_mins and reason are the properties available to this resource.

Actions

The reboot resource has the following actions:

:cancel
Cancel a reboot request.
: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.
:reboot_now
Reboot a node so that the chef-client may continue the installation process.
:request_reboot
Reboot a node at the end of a chef-client run.

Properties

The reboot resource has the following properties:

delay_mins

Ruby Type: Integer | Default Value: 0

The amount of time (in minutes) to delay a reboot request.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the chef-client run at which a notification is run. The following timer is available:

:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.
reason

Ruby Type: String

A string that describes the reboot action.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the chef-client run at which a notification is run. The following timer is available:

:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

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.

Reboot a node immediately

reboot 'now' do
  action :nothing
  reason 'Cannot continue Chef run without a reboot.'
  delay_mins 2
end

execute 'foo' do
  command '...'
  notifies :reboot_now, 'reboot[now]', :immediately
end

Reboot a node at the end of a chef-client run

reboot 'app_requires_reboot' do
  action :request_reboot
  reason 'Need to reboot when the run completes successfully.'
  delay_mins 5
end

Cancel a reboot

reboot 'cancel_reboot_request' do
  action :cancel
  reason 'Cancel a previous end-of-run reboot request.'
end

Rename computer, join domain, reboot

The following example shows how to rename a computer, join a domain, and then reboot the computer:

reboot 'Restart Computer' do
  action :nothing
end

powershell_script 'Rename and Join Domain' do
  code <<-EOH
    ...your rename and domain join logic here...
  EOH
  not_if <<-EOH
    $ComputerSystem = gwmi win32_computersystem
    ($ComputerSystem.Name -like '#{node['some_attribute_that_has_the_new_name']}') -and
      $ComputerSystem.partofdomain)
  EOH
  notifies :reboot_now, 'reboot[Restart Computer]', :immediately
end

where:

  • The powershell_script resource block renames a computer, and then joins a domain
  • The reboot resource restarts the computer
  • The not_if guard prevents the Windows PowerShell script from running when the settings in the not_if guard match the desired state
  • The notifies statement tells the reboot resource block to run if the powershell_script block was executed during the chef-client run

registry_key resource

[edit on GitHub]

Use the registry_key resource to create and delete registry keys in Microsoft Windows.

Note

64-bit versions of Microsoft Windows have a 32-bit compatibility layer in the registry that reflects and redirects certain keys (and their values) into specific locations (or logical views) of the registry hive.

The chef-client can access any reflected or redirected registry key. The machine architecture of the system on which the chef-client is running is used as the default (non-redirected) location. Access to the SysWow64 location is redirected must be specified. Typically, this is only necessary to ensure compatibility with 32-bit applications that are running on a 64-bit operating system.

32-bit versions of the chef-client (12.8 and earlier) and 64-bit versions of the chef-client (12.9 and later) generally behave the same in this situation, with one exception: it is only possible to read and write from a redirected registry location using chef-client version 12.9 (and later).

For more information, see: Registry Reflection.

Syntax

A registry_key resource block creates and deletes registry keys in Microsoft Windows:

registry_key "HKEY_LOCAL_MACHINE\\...\\System" do
  values [{
    name: "NewRegistryKeyValue",
    type: :multi_string,
    data: ['foo\0bar\0\0']
  }]
  action :create
end

Use multiple registry key entries with key values that are based on node attributes:

registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\name_of_registry_key' do
  values [{name: 'key_name', type: :string, data: 'C:\Windows\System32\file_name.bmp'},
          {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']},
          {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']}
         ]
  action :create
end

The full syntax for all of the properties that are available to the registry_key resource is:

registry_key 'name' do
  architecture      Symbol # default value: machine
  key               String # default value: 'name' unless specified
  recursive         true, false # default value: false
  values
  action            Symbol # defaults to :create if not specified
end

where

  • registry_key is the resource

  • name is the name of the resource block

  • values is a hash that contains at least one registry key to be created or deleted. Each registry key in the hash is grouped by brackets in which the name:, type:, and data: values for that registry key are specified.

  • type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.

    Warning

    :multi_string must be an array, even if there is only a single string.

  • action identifies the steps the chef-client will take to bring the node into the desired state

  • architecture, key, recursive and values 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.

Registry Key Path Separators

A Microsoft Windows registry key can be used as a string in Ruby code, such as when a registry key is used as the name of a recipe. In Ruby, when a registry key is enclosed in a double-quoted string (" "), the same backslash character (\) that is used to define the registry key path separator is also used in Ruby to define an escape character. Therefore, the registry key path separators must be escaped when they are enclosed in a double-quoted string. For example, the following registry key:

HKCU\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Themes

may be enclosed in a single-quoted string with a single backslash:

'HKCU\SOFTWARE\path\to\key\Themes'

or may be enclosed in a double-quoted string with an extra backslash as an escape character:

"HKCU\\SOFTWARE\\path\\to\\key\\Themes"

Recipe DSL Methods

Six methods are present in the Recipe DSL to help verify the registry during a chef-client run on the Microsoft Windows platform—registry_data_exists?, registry_get_subkeys, registry_get_values, registry_has_subkeys?, registry_key_exists?, and registry_value_exists?—these helpers ensure the powershell_script resource is idempotent.

The recommended order in which registry key-specific methods should be used within a recipe is: key_exists?, value_exists?, data_exists?, get_values, has_subkeys?, and then get_subkeys.

registry_data_exists?

Use the registry_data_exists? method to find out if a Microsoft Windows registry key contains the specified data of the specified type under the value.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_data_exists? method is as follows:

registry_data_exists?(
  KEY_PATH,
  { name: 'NAME', type: TYPE, data: DATA },
  ARCHITECTURE
)

where:

  • KEY_PATH is the path to the registry key value. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • { name: 'NAME', type: TYPE, data: DATA } is a hash that contains the expected name, type, and data of the registry key value
  • type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

registry_get_subkeys

Use the registry_get_subkeys method to get a list of registry key values that are present for a Microsoft Windows registry key.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_get_subkeys method is as follows:

subkey_array = registry_get_subkeys(KEY_PATH, ARCHITECTURE)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This returns an array of registry key values.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

registry_get_values

Use the registry_get_values method to get the registry key values (name, type, and data) for a Microsoft Windows registry key.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_get_values method is as follows:

subkey_array = registry_get_values(KEY_PATH, ARCHITECTURE)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This returns an array of registry key values.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

registry_has_subkeys?

Use the registry_has_subkeys? method to find out if a Microsoft Windows registry key has one (or more) values.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_has_subkeys? method is as follows:

registry_has_subkeys?(KEY_PATH, ARCHITECTURE)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

registry_key_exists?

Use the registry_key_exists? method to find out if a Microsoft Windows registry key exists at the specified path.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_key_exists? method is as follows:

registry_key_exists?(KEY_PATH, ARCHITECTURE)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false. (Any registry key values that are associated with this registry key are ignored.)

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

registry_value_exists?

Use the registry_value_exists? method to find out if a registry key value exists. Use registry_data_exists? to test for the type and data of a registry key value.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_value_exists? method is as follows:

registry_value_exists?(
  KEY_PATH,
  { name: 'NAME' },
  ARCHITECTURE
)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • { name: 'NAME' } is a hash that contains the name of the registry key value; if either type: or :value are specified in the hash, they are ignored
  • type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

Actions

This resource has the following actions:

:create
Default. Create a registry key. If a registry key already exists (but does not match), update that registry key to match.
:create_if_missing
Create a registry key if it does not exist. Also, create a registry key value if it does not exist.
:delete
Delete the specified values for a registry key.
:delete_key
Delete the specified registry key and all of its subkeys.
: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.

Note

Be careful when using the :delete_key action with the recursive attribute. This will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by the chef-client.

Properties

This resource has the following properties:

architecture

Ruby Type: Symbol | Default Value: :machine

The architecture of the node for which keys are to be created or deleted. Possible values: :i386 (for nodes with a 32-bit registry), :x86_64 (for nodes with a 64-bit registry), and :machine (to have the chef-client determine the architecture during the chef-client run).

In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

key

Ruby Type: String

The path to the location in which a registry key is to be created or from which a registry key is to be deleted. Default value: the name of the resource block. See “Syntax” section above for more information. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
recursive

Ruby Type: true, false

When creating a key, this value specifies that the required keys for the specified path are to be created. When using the :delete_key action in a recipe, and if the registry key has subkeys, then set the value for this property to true.

Note

Be careful when using the :delete_key action with the recursive attribute. This will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by the chef-client.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Determines whether or not sensitive resource data (such as key information) is logged by Chef Client.

New in Chef Client 14.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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
values

Ruby Type: Hash, Array

An array of hashes, where each Hash contains the values that are to be set under a registry key. Each Hash must contain name:, type:, and data: (and must contain no other key values).

type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.

Warning

:multi_string must be an array, even if there is only a single string.

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 registry key

Use a double-quoted string:

registry_key "HKEY_LOCAL_MACHINE\\path-to-key\\Policies\\System" do
  values [{
    name: 'EnableLUA',
    type: :dword,
    data: 0
  }]
  action :create
end

or a single-quoted string:

registry_key 'HKEY_LOCAL_MACHINE\path-to-key\Policies\System' do
  values [{
    name: 'EnableLUA',
    type: :dword,
    data: 0
  }]
  action :create
end

Delete a registry key value

Use a double-quoted string:

registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\path\\to\\key\\AU" do
  values [{
    name: 'NoAutoRebootWithLoggedOnUsers',
    type: :dword,
    data: ''
    }]
  action :delete
end

or a single-quoted string:

registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\path\to\key\AU' do
  values [{
    name: 'NoAutoRebootWithLoggedOnUsers',
    type: :dword,
    data: ''
    }]
  action :delete
end

Note

If data: is not specified, you get an error: Missing data key in RegistryKey values hash

Delete a registry key and its subkeys, recursively

Use a double-quoted string:

registry_key "HKCU\\SOFTWARE\\Policies\\path\\to\\key\\Themes" do
  recursive true
  action :delete_key
end

or a single-quoted string:

registry_key 'HKCU\SOFTWARE\Policies\path\to\key\Themes' do
  recursive true
  action :delete_key
end

Note

Be careful when using the :delete_key action with the recursive attribute. This will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by the chef-client.

Use re-directed keys

In 64-bit versions of Microsoft Windows, HKEY_LOCAL_MACHINE\SOFTWARE\Example is a re-directed key. In the following examples, because HKEY_LOCAL_MACHINE\SOFTWARE\Example is a 32-bit key, the output will be “Found 32-bit key” if they are run on a version of Microsoft Windows that is 64-bit:

registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do
  architecture :i386
  recursive true
  action :create
end

or:

registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do
  architecture :x86_64
  recursive true
  action :delete_key
end

or:

ruby_block 'check 32-bit' do
  block do
    puts 'Found 32-bit key'
  end
  only_if {
    registry_key_exists?("HKEY_LOCAL_MACHINE\SOFTWARE\\Example",
    :i386)
  }
end

or:

ruby_block 'check 64-bit' do
  block do
    puts 'Found 64-bit key'
  end
  only_if {
    registry_key_exists?("HKEY_LOCAL_MACHINE\\SOFTWARE\\Example",
    :x86_64)
  }
end

Set proxy settings to be the same as those used by the chef-client

Use a double-quoted string:

proxy = URI.parse(Chef::Config[:http_proxy])
registry_key "HKCU\Software\Microsoft\path\to\key\Internet Settings" do
  values [{name: 'ProxyEnable', type: :reg_dword, data: 1},
          {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"},
          {name: 'ProxyOverride', type: :reg_string, data: <local>},
         ]
  action :create
end

or a single-quoted string:

proxy = URI.parse(Chef::Config[:http_proxy])
registry_key 'HKCU\Software\Microsoft\path\to\key\Internet Settings' do
  values [{name: 'ProxyEnable', type: :reg_dword, data: 1},
          {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"},
          {name: 'ProxyOverride', type: :reg_string, data: <local>},
         ]
  action :create
end

Set the name of a registry key to “(Default)”

Use a double-quoted string:

registry_key 'Set (Default) value' do
  key "HKLM\\Software\\Test\\Key\\Path"
  values [
    {name: '', type: :string, data: 'test'},
  ]
  action :create
end

or a single-quoted string:

registry_key 'Set (Default) value' do
  key 'HKLM\Software\Test\Key\Path'
  values [
    {name: '', type: :string, data: 'test'},
  ]
  action :create
end

where name: '' contains an empty string, which will set the name of the registry key to (Default).

remote_directory resource

[edit on GitHub]

Use the remote_directory resource to incrementally transfer a directory from a cookbook to a node. The directory that is copied from the cookbook should be located under COOKBOOK_NAME/files/default/REMOTE_DIRECTORY. The remote_directory resource will obey file specificity.

Syntax

A remote_directory resource block transfers a directory from a cookbook to a node, and then assigns the permissions needed on that directory. For example:

remote_directory '/etc/apache2' do
  source 'apache2'
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

where

  • '/etc/apache2' specifies the directory
  • source specifies a directory in the current cookbook (use the cookbook property to specify a file that is in a different cookbook)
  • owner, group, and mode define the permissions

The full syntax for all of the properties that are available to the remote_directory resource is:

remote_directory 'name' do
  cookbook                   String
  files_backup               Integer, false
  files_group                String
  files_mode                 String
  files_owner                String
  group                      String, Integer
  inherits                   true, false
  mode                       String, Integer
  notifies                   # see description
  overwrite                  true, false
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  purge                      true, false
  recursive                  true, false
  rights                     Hash
  source                     String
  subscribes                 # see description
  action                     Symbol # defaults to :create if not specified
end

where:

  • remote_directory is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • cookbook, files_backup, files_group, files_mode, files_owner, group, mode, overwrite, owner, path, purge, recursive, and source are the properties available to this resource.

Actions

The remote_directory resource has the following actions:

:create
Default. Create a directory and/or the contents of that directory. If a directory or its contents already exist (but does not match), update that directory or its contents to match.
:create_if_missing
Create a directory and/or the contents of that directory, but only if it does not exist.
:delete
Delete a directory, including the contents of that 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

The remote_directory resource has the following properties:

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.

files_backup

Ruby Type: Integer, false | Default Value: 5

The number of backup copies to keep for files in the directory.

files_group

Ruby Type: String

Configure group permissions for files. 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).

files_mode

Ruby Type: String

The octal mode for a file.

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.

files_owner

Ruby Type: String

Configure owner permissions for files. 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).

group

Ruby Type: Integer, String

Use to configure permissions for directories. 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 Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

inherits

Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

mode

Ruby Type: 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 notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
overwrite

Ruby Type: true, false | Default Value: true

Overwrite a file when it is different.

owner

Ruby Type: Integer, String

Use to configure permissions for directories. 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.

purge

Ruby Type: true, false | Default Value: false

Purge extra files found in the target directory.

recursive

Ruby Type: true, false

Create or delete directories recursively. Default value: true; the chef-client must be able to create the directory structure, including parent directories (if missing), as defined in COOKBOOK_NAME/files/default/REMOTE_DIRECTORY.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

rights

Ruby Type: 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 Type: String

The base name of the source file (and inferred from the path property).

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Recursive Directories

The remote_directory resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the recursive attribute only applies group, mode, and owner attribute values to the remote directory itself and any inner directories the resource copies.

A directory structure:

/foo
  /bar
    /baz

The following example shows a way create a file in the /baz directory:

remote_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|
  remote_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.

Example

This section contains a more detailed example of how the chef-client manages recursive directory structures:

  • A cookbook named cumbria that is used to build a website
  • A subfolder in the /files/default directory named /website
  • A file named index.html, which is the root page for the website
  • Directories within /website named /cities, /places, and /football, which contains pages about cities, places, and football teams
  • A directory named /images, which contains images

These files are placed in the /files/default directory in the cumbria cookbook, like this:

cumbria
  /files
    /default
      /website
        index.html
        /cities
          carisle.html
          kendal.html
          penrith.html
          windermere.html
        /football
          carisle_united.html
        /images
          carisle_united.png
          furness_abbey.png
          hadrians_wall.png
          kendal.png
        /places
          furness_abbey.html
          hadrians_wall.html

The remote_directory resource can be used to build a website using these files. This website is being run on an Apache web server. The resource would be similar to the following:

remote_directory "/var/www/html" do
  files_mode '0440'
  files_owner 'yan'
  mode '0770'
  owner 'hamilton'
  source "website"
end

When the chef-client runs, the remote_directory resource will tell the chef-client to copy the directory tree from the cookbook to the file system using the structure defined in cookbook:

/var
  /www
    /html
      index.html
      /cities
        carisle.html
        kendal.html
        penrith.html
        windermere.html
      /football
        carisle_united.html
      /images
        carisle_united.png
        furness_abbey.png
        hadrians_wall.png
        kendal.png
      /places
        furness_abbey.html
        hadrians_wall.html

The chef-client will manage the permissions of the entire directory structure below /html, for a total of 12 files and 4 directories. For example:

dr-xr-xr-x 2 root     root 4096 /var/www/html
dr--r----- 1 yan      root 4096 /var/www/html/index.html
drwxrwx--- 2 hamilton root 4096 /var/www/html/cities
dr--r----- 1 yan      root 4096 /var/www/html/cities/carlisle.html
dr--r----- 1 yan      root 4096 /var/www/html/cities/kendal.html
dr--r----- 1 yan      root 4096 /var/www/html/cities/penrith.html
dr--r----- 1 yan      root 4096 /var/www/html/cities/windermere.html
drwxrwx--- 2 hamilton root 4096 /var/www/html/football
dr--r----- 1 yan      root 4096 /var/www/html/football/carlisle_united.html
drwxrwx--- 2 hamilton root 4096 /var/www/html/images
dr--r----- 1 yan      root 4096 /var/www/html/images/carlisle_united/png
dr--r----- 1 yan      root 4096 /var/www/html/images/furness_abbey/png
dr--r----- 1 yan      root 4096 /var/www/html/images/hadrians_wall.png
dr--r----- 1 yan      root 4096 /var/www/html/images/kendal.png
drwxrwx--- 2 hamilton root 4096 /var/www/html/places
dr--r----- 1 yan      root 4096 /var/www/html/places/furness_abbey.html
dr--r----- 1 yan      root 4096 /var/www/html/places/hadrians_wall.html

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.

Recursively transfer a directory from a remote location

# create up to 10 backups of the files
# set the files owner different from the directory
remote_directory '/tmp/remote_something' do
  source 'something'
  files_backup 10
  files_owner 'root'
  files_group 'root'
  files_mode '0644'
  owner 'nobody'
  group 'nobody'
  mode '0755'
end

Use with the chef_handler resource

The following example shows how to use the remote_directory resource and the chef_handler resource to reboot a handler named WindowsRebootHandler:

# the following code sample comes from the
# ``reboot_handler`` recipe in the ``windows`` cookbook:
# https://github.com/chef-cookbooks/windows

remote_directory node['chef_handler']['handler_path'] do
  source 'handlers'
  recursive true
  action :create
end

chef_handler 'WindowsRebootHandler' do
  source "#{node['chef_handler']['handler_path']}/windows_reboot_handler.rb"
  arguments node['windows']['allow_pending_reboots']
  supports :report => true, :exception => false
  action :enable
end

remote_file resource

[edit on GitHub]

Use the remote_file resource to transfer a file from a remote location using file specificity. This resource is similar to the file resource.

Note

Fetching files from the files/ directory in a cookbook should be done with the cookbook_file resource.

Changed in 12.4 to support Microsoft Windows UNC.

Syntax

A remote_file resource block manages files by using files that exist remotely. For example, to write the home page for an Apache website:

remote_file '/var/www/customers/public_html/index.html' do
  source 'http://somesite.com/index.html'
  owner 'web_admin'
  group 'web_admin'
  mode '0755'
  action :create
end

where

  • '/var/www/customers/public_html/index.html' is path to the file to be created
  • 'http://somesite.com/index.html' specifies the location of the remote file, the file is downloaded from there
  • owner, group, and mode define the permissions

The full syntax for all of the properties that are available to the remote_file resource is:

remote_file 'name' do
  atomic_update              true, false
  authentication             # default value: remote
  backup                     Integer, false # default value: 5
  checksum                   String
  content                    String, nil
  diff                       String, nil
  force_unlink               true, false # default value: false
  ftp_active_mode            true, false # default value: false
  group                      String, Integer
  headers                    Hash
  inherits                   true, false
  manage_symlink_source      true, false
  mode                       String, Integer
  notifies                   # see description
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  rights                     Hash
  source                     String, Array
  subscribes                 # see description
  use_conditional_get        true, false
  verify                     String, Block
  remote_domain              String
  remote_password            String
  remote_user                String
  show_progress              true, false # default value: false
  use_etag                   true, false # default value: true
  use_last_modified          true, false # default value: true
  verifications              Array
  action                     Symbol # defaults to :create if not specified
end

where:

  • remote_file is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • atomic_update, authentication, backup, checksum, content, diff, force_unlink, ftp_active_mode, group, headers, manage_symlink_source, mode, owner, path, remote_domain, remote_password, remote_user, show_progress, use_etag, use_last_modified, and verifications are the properties available to 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 Type: true, false | Default Value: true

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.

backup

Ruby Type: false, Integer | Default Value: 5

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.

checksum

Ruby Type: String

Optional, see use_conditional_get. The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, the chef-client does not download it.

force_unlink

Ruby Type: true, false | Default Value: false

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.

ftp_active_mode

Ruby Type: true, false | Default Value: false

Whether the chef-client uses active or passive FTP. Set to true to use active FTP.

group

Ruby Type: 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).

headers()

Ruby Type: Hash | Default Value: {}

A Hash of custom headers. For example:

headers({ "Cookie" => "user=grantmc; pass=p@ssw0rd!" })

or:

headers({ "Referer" => "#{header}" })

or:

headers( "Authorization"=>"Basic #{ Base64.encode64("#{username}:#{password}").gsub("\n", "") }" )
ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

inherits

Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

manage_symlink_source

Ruby Type: true, false | Default Value: true (with warning)

Change the behavior of the file resource if it is pointed at a symlink. When this value is set to true, the Chef client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to false, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file.

The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning.

mode

Ruby Type: 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 notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
owner

Ruby Type: 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. Default value: the name of the resource block. See “Syntax” section above for more information.

remote_user

Ruby Type: String

Windows only The name of a user with access to the remote file specified by the source property. The user name may optionally be specified with a domain, such as: domain\user or user@my.dns.domain.com via Universal Principal Name (UPN) format. The domain may also be set using the remote_domain property. Note that this property is ignored if source is not a UNC path. If this property is specified, the remote_password property is required.

New in Chef client 13.4

remote_password

Ruby Type: String

Windows only The password of the user specified by the remote_user property. This property is required if remote_user is specified and may only be specified if remote_user is specified. The sensitive property for this resource will automatically be set to true if remote_password is specified.

New in Chef client 13.4

remote_domain

Ruby Type: String

Windows only The domain of the user specified by the remote_user property. By default the resource will authenticate against the domain of the remote system, or as a local account if the remote system is not joined to a domain. If the remote system is not part of a domain, it is necessary to authenticate as a local user on the remote system by setting the domain to ., for example: remote_domain ".". The domain may also be specified as part of the remote_user property.

New in Chef client 13.4

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

rights

Ruby Type: 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 Type: String, Array

Required. The location of the source file. The location of the source file may be HTTP (http://), FTP (ftp://), SFTP (sftp://), local (file:///), or UNC (\\host\share\file.tar.gz).

There are many ways to define the location of a source file. By using a path:

source 'http://couchdb.apache.org/img/sketch.png'

By using FTP:

source 'ftp://remote_host/path/to/img/sketch.png'

By using SFTP:

source 'sftp://username:password@remote_host:22/path/to/img/sketch.png'

By using a local path:

source 'file:///path/to/img/sketch.png'

By using a Microsoft Windows UNC:

source '\\\\path\\to\\img\\sketch.png'

By using a node attribute:

source node['nginx']['foo123']['url']

By using attributes to define paths:

source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2"

By defining multiple paths for multiple locations:

source 'http://seapower/spring.png', 'http://seapower/has_sprung.png'

By defining those same multiple paths as an array:

source ['http://seapower/spring.png', 'http://seapower/has_sprung.png']

When multiple paths are specified, the chef-client will attempt to download the files in the order listed, stopping after the first successful download.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
use_conditional_get

Ruby Type: true, false | Default Value: true

Enable conditional HTTP requests by using a conditional GET (with the If-Modified-Since header) or an opaque identifier (ETag). To use If-Modified-Since headers, use_last_modified must also be set to true. To use ETag headers, use_etag must also be set to true.

use_etag

Ruby Type: true, false | Default Value: true

Enable ETag headers. Set to false to disable ETag headers. To use this setting, use_conditional_get must also be set to true.

use_last_modified

Ruby Type: true, false | Default Value: true

Enable If-Modified-Since headers. Set to false to disable If-Modified-Since headers. To use this setting, use_conditional_get must also be set to true.

show_progess

Ruby Type: true, false | Default Value: false

Displays the progress of the file download. Set to true to enable this feature.

verify

Ruby Type: 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:

remote_file '/tmp/baz' do
  verify { 1 == 1 }
end

This should return true:

remote_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:

remote_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:

remote_file '/tmp/bar' do
  verify { 1 == 1}
end

And this should return true:

remote_file '/tmp/foo' do
  verify do |path|
    true
  end
end

Whereas, this should return false:

remote_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.

Prevent Re-downloads

To prevent the chef-client from re-downloading files that are already present on a node, use one of the following attributes in a recipe: use_conditional_get (default) or checksum.

  • The use_conditional_get attribute is the default behavior of the chef-client. If the remote file is located on a server that supports ETag and/or If-Modified-Since headers, the chef-client will use a conditional GET to determine if the file has been updated. If the file has been updated, the chef-client will re-download the file.
  • The checksum attribute will ask the chef-client to compare the checksum for the local file to the one at the remote location. If they match, the chef-client will not re-download the file. Using a local checksum for comparison requires that the local checksum be the correct checksum.

The desired approach just depends on the desired workflow. For example, if a node requires a new file every day, using the checksum approach would require that the local checksum be updated and/or verified every day as well, in order to ensure that the local checksum was the correct one. Using a conditional GET in this scenario will greatly simplify the management required to ensure files are being updated accurately.

Access a remote UNC path on Windows

The remote_file resource on Windows supports accessing files from a remote SMB/CIFS share. The file name should be specified in the source property as a UNC path e.g. \\myserver\myshare\mydirectory\myfile.txt. This allows access to the file at that path location even if the Chef client process identity does not have permission to access the file. Credentials for authenticating to the remote system can be specified using the remote_user, remote_domain, and remote_password properties when the user that the Chef client is running does not have access to the remote file. See the “Properties” section for more details on these options.

Note: This is primarily for accessing remote files when the user that the Chef client is running as does not have sufficient access, and alternative credentials need to be specified. If the user already has access, the credentials do not need to be specified. In a case where the local system and remote system are in the same domain, the remote_user and remote_password properties often do not need to be specified, as the user may already have access to the remote file share.

Examples:

Access a file from a different domain account:

remote_file "E:/domain_test.txt"  do
  source  "\\\\myserver\\myshare\\mydirectory\\myfile.txt"
  remote_domain "domain"
  remote_user "username"
  remote_password "password"
end

OR

remote_file "E:/domain_test.txt"  do
  source  "\\\\myserver\\myshare\\mydirectory\\myfile.txt"
  remote_user "domain\\username"
  remote_password "password"
end

Access a file using a local account on the remote machine:

remote_file "E:/domain_test.txt"  do
  source  "\\\\myserver\\myshare\\mydirectory\\myfile.txt"
  remote_domain "."
  remote_user "username"
  remote_password "password"
end

OR

remote_file "E:/domain_test.txt"  do
  source  "\\\\myserver\\myshare\\mydirectory\\myfile.txt"
  remote_user ".\\username"
  remote_password "password"
end

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 from a URL

remote_file '/tmp/testfile' do
  source 'http://www.example.com/tempfiles/testfile'
  mode '0755'
  checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file.
end

Transfer a file only when the source has changed

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

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

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

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

Specify local Windows file path as a valid URI

When specifying a local Microsoft Windows file path as a valid file URI, an additional forward slash (/) is required. For example:

remote_file 'file:///c:/path/to/file' do
  ...       # other attributes
end

rhsm_errata_level resource

[edit on GitHub]

Use the rhsm_errata_level resource to install all packages of a specified errata level from the Red Hat Subscription Manager. For example, you can ensure that all packages associated with errata marked at a “Critical” security level are installed.

The available errata levels are: critical, moderate, important, and low.

New in Chef Client 14.0.

Syntax

The rhsm_errata_level resource has the following syntax:

rhsm_errata_level 'name' do
  errata_level               String # default value: 'name'
  notifies                   # see description
  subscribes                 # see description
  action                     Symbol # defaults to :install if not specified
end

where:

  • rhsm_errata_level is the resource.
  • 'name' is the errata level to install packages from, or the resource name
  • errata_level, notifies, and subscribes are the properties available to this resource

Actions

The rhsm_errata_level resource has the following actions:

:install
Default. Install all packages of the specified errata level.
: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

The rhsm_errata_level resource has the following properties:

errata_level

Ruby Type: String

The errata level of packages to install, if it differs from the resource name.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples

Install all files from the “important” errata level

rhsm_errata_level 'important'

Specify an errata level that differs from the resource name

rhsm_errata_level 'example_install_moderate' do
  errata_level 'moderate'
end

rhsm_errata resource

[edit on GitHub]

Use the rhsm_errata resource to install packages associated with a given Red Hat Subscription Manager Errata ID. This is helpful if packages that mitigate a single vulnerability must be installed on your hosts.

New in Chef Client 14.0.

Syntax

The rhsm_errata resource has the following syntax:

rhsm_errata 'name' do
  errata_id                  String # default value: 'name'
  notifies                   # see description
  subscribes                 # see description
  action                     Symbol # defaults to :install if not specified

where:

  • rhsm_errata is the resource
  • 'name' is the Subscription Manager Errata ID, or the resource name
  • errata_id, notifies, and subscribes are the properties available to this resource

Actions

The rhsm_errata resource has the following actions:

:install
Default. Install a package for a specific errata ID.
: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

errata_id

Ruby Type: String

Specify the Errata ID if it differs from the resource name.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples

Install a package from an Errata ID

rhsm_errata 'RHSA:2018-1234'

Specify an Errata ID that differs from the resource name

rhsm_errata 'errata-install'
  errata_id 'RHSA:2018-1234'
end

rhsm_register resource

[edit on GitHub]

Use the rhsm_register resource to register a node with the Red Hat Subscription Manager or a local Red Hat Satellite server.

New in Chef Client 14.0.

Syntax

The rhsm_register resource has the following syntax:

rhsm_register 'name' do
  activation_key             String, Array
  auto_attach                true, false # default value: false
  environment                String
  force                      true, false # default value: false
  install_katello_agent      true, false # default value: true
  organization               String
  password                   String
  satellite_host             String
  username                   String
  action                     Symbol # defaults to :register if not specified
end

where:

  • rhsm_register is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • activation_key, auto_attach, environment, force, install_katello_agent, organization, password, satellite_host, and username are the properties available to this resource.

Actions

:register
Default. Register the node with RHSM.
:unregister
Unregister the node from RHSM.
: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

activation_key

Ruby Type: String, Array

A string or array of activation keys to use when registering; you must also specify the organization property when using this.

auto_attach

Ruby Type: true, false | Default Value: false

If true, RHSM will attempt to automatically attach the host to applicable subscriptions. It is generally better to use an activation key with the subscriptions predefined.

environment

Ruby Type: String

The environment to use when registering; required when using the username and password properties.

force

Ruby Type: true, false | Default Value: false

If true, the system will be registered even if it is already registered. Normally, any register operations will fail if the machine has already been registered.

install_katello_agent

Ruby Type: true, false | Default Value: true

If true, the katello-agent RPM will be installed.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
organization

Ruby Type: String

The organization to use when registering; required when using the activation_key property.

password

Ruby Type: String

The password to use when registering. This property is not applicable if using an activation key. If specified, username and environment are also required.

satellite_host

Ruby Type: String

The FQDN of the Satellite host to register with. If this property is not specified, the host will register with Red Hat’s public RHSM service.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

rhsm_repo resource

[edit on GitHub]

Use the rhsm_repo resource to enable or disable Red Hat Subscription Manager repositories that are made available via attached subscriptions.

New in Chef Client 14.0.

Syntax

The rhsm_repo resource has the following syntax:

rhsm_repo 'name' do
  repo_name      String # default value: 'name' unless specified
  action         Symbol # defaults to :enable if not specified
end

where:

  • rhsm_repo is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • repo_name is the property available to this resource.

Actions

:enable
Default. Enable an RHSM repository.
:disable
Disable an RHSM repository.
: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

repo_name

Ruby Type: String

An optional property for specifying the repository name if it differs from the resource’s name.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples

Enable an RHSM repository

rhsm_repo 'rhel-7-server-extras-rpms'

Disable an RHSM repository

rhsm_repo 'rhel-7-server-extras-rpms' do
  action :disable
end

rhsm_subscription resource

[edit on GitHub]

Use the rhsm_subscription resource to add or remove Red Hat Subscription Manager subscriptions from your host. This can be used when a host’s activation_key does not attach all necessary subscriptions to your host.

New in Chef Client 14.0.

Syntax

The rhsm_subscription resource has the following syntax:

rhsm_subscription 'name' do
  pool_id      String # default value: 'name' unless specified
  action       Symbol # defaults to :attach if not specified
end

where:

  • rhsm_subscription is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • pool_id is the property available to this resource.

Actions

:attach
Default. Attach the node to a subscription pool.
:remove
Remove the node from a subscription pool.
: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

pool_id

Ruby Type: String

An optional property for specifying the Pool ID if it differs from the resource’s name.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

route resource

[edit on GitHub]

Use the route resource to manage the system routing table in a Linux environment.

Syntax

A route resource block manages the system routing table in a Linux environment:

route '10.0.1.10/32' do
  gateway '10.0.0.20'
  device 'eth1'
end

The full syntax for all of the properties that are available to the route resource is:

route 'name' do
  comment                    String
  device                     String
  gateway                    String
  netmask                    String
  notifies                   # see description
  subscribes                 # see description
  target                     String # defaults to 'name' if not specified
  action                     Symbol # defaults to :add if not specified
end

where

  • route is the resource
  • name is the name of the resource block. When the name is default, the default gateway is modified and added to a file under /etc/sysconfig/network` on RHEL and CentOS nodes.
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • device, gateway, netmask, and target 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. Add a route.
:delete
Delete a route.
: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:

comment

Ruby Type: String

Add a comment.

New in Chef Client 14.0.

device

Ruby Type: String

The network interface to which the route applies.

gateway

Ruby Type: String

The gateway for the route.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

netmask

Ruby Type: String

The decimal representation of the network mask. For example: 255.255.255.0.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
target

Ruby Type: String

The IP address of the target route. Default value: the name of the resource block. See “Syntax” section above for more information.

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.

Add a host route

route '10.0.1.10/32' do
  gateway '10.0.0.20'
  device 'eth1'
end

Add a default route

route 'default' do
  gateway '10.0.0.20'
end

Delete a network route

route '10.1.1.0/24' do
  gateway '10.0.0.20'
  action :delete
end

rpm_package resource

[edit on GitHub]

Use the rpm_package resource to manage packages for the RPM Package Manager 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 rpm_package resource block manages a package on a node, typically by installing it. The simplest use of the rpm_package resource is:

rpm_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 rpm_package resource is:

rpm_package 'name' do
  allow_downgrade            true, false
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where

  • rpm_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
  • allow_downgrade, options, package_name, 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.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties

This resource has the following properties:

allow_downgrade

Ruby Type: true, false

Downgrade a package to satisfy requested version requirements.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
options

Ruby Type: String

One (or more) additional options that are passed to the command.

package_name

Ruby Type: String, Array

The name of the package. Default value: the name of the resource block. See “Syntax” section above for more information.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

rpm_package 'name of package' do
  action :install
end

ruby resource

[edit on GitHub]

Use the ruby resource to execute scripts using the Ruby 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 ruby 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 ruby resource block executes scripts using Ruby:

ruby '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 ruby resource is:

ruby 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  notifies                   # see description
  path                       Array
  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

  • ruby 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, 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 Type: String, Integer

The group name or group ID that must be changed before running a command.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
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:

ruby 'mycommand' do
  environment 'PATH' => "/my/path/to/bin:#{ENV['PATH']}"
end
retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

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.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: Integer, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

user

Ruby Type: String, Integer

The user name or user ID that should be changed before running a command.

umask

Ruby Type: 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

Examples

None.

ruby_block resource

[edit on GitHub]

Use the ruby_block resource to execute Ruby code during a chef-client run. Ruby code in the ruby_block resource is evaluated with other resources during convergence, whereas Ruby code outside of a ruby_block resource is evaluated before other resources, as the recipe is compiled.

Syntax

A ruby_block resource block executes a block of arbitrary Ruby code. For example, to reload the client.rb file during the chef-client run:

ruby_block 'reload_client_config' do
  block do
    Chef::Config.from_file("/etc/chef/client.rb")
  end
  action :run
end

The full syntax for all of the properties that are available to the ruby_block resource is:

ruby_block 'name' do
  block                      Block
  block_name                 String # defaults to 'name' if not specified
  notifies                   # see description
  subscribes                 # see description
  action                     Symbol # defaults to :run if not specified
end

where

  • ruby_block is the resource
  • name is the name of the resource block
  • block is the block of Ruby code to be executed
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • block and block_name 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
The same as :run.
: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. Run a Ruby block.

Properties

This resource has the following properties:

block

Ruby Type: Block

A block of Ruby code.

block_name

Ruby Type: String

The name of the Ruby block. Default value: the name of the resource block. See “Syntax” section above for more information.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

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.

Re-read configuration data

ruby_block 'reload_client_config' do
  block do
    Chef::Config.from_file('/etc/chef/client.rb')
  end
  action :run
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 an if statement with the platform recipe DSL method

The following example shows how an if statement can be used with the platform? method in the Recipe DSL to run code specific to Microsoft Windows. The code is defined using the ruby_block resource:

# the following code sample comes from the ``client`` recipe
# in the following cookbook: https://github.com/chef-cookbooks/mysql

if platform?('windows')
  ruby_block 'copy libmysql.dll into ruby path' do
    block do
      require 'fileutils'
      FileUtils.cp "#{node['mysql']['client']['lib_dir']}\\libmysql.dll",
        node['mysql']['client']['ruby_dir']
    end
    not_if { File.exist?("#{node['mysql']['client']['ruby_dir']}\\libmysql.dll") }
  end
end

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

Update the /etc/hosts file

The following example shows how the ruby_block resource can be used to update the /etc/hosts file:

# the following code sample comes from the ``ec2`` recipe
# in the following cookbook: https://github.com/chef-cookbooks/dynect

ruby_block 'edit etc hosts' do
  block do
    rc = Chef::Util::FileEdit.new('/etc/hosts')
    rc.search_file_replace_line(/^127\.0\.0\.1 localhost$/,
       '127.0.0.1 #{new_fqdn} #{new_hostname} localhost')
    rc.write_file
  end
end

Set environment variables

The following example shows how to use variables within a Ruby block to set environment variables using rbenv.

node.override[:rbenv][:root] = rbenv_root
node.override[:ruby_build][:bin_path] = rbenv_binary_path

ruby_block 'initialize' do
  block do
    ENV['RBENV_ROOT'] = node[:rbenv][:root]
    ENV['PATH'] = "#{node[:rbenv][:root]}/bin:#{node[:ruby_build][:bin_path]}:#{ENV['PATH']}"
  end
end

Set JAVA_HOME

The following example shows how to use a variable within a Ruby block to set the java_home environment variable:

ruby_block 'set-env-java-home' do
  block do
    ENV['JAVA_HOME'] = java_home
  end
end

Run specific blocks of Ruby code on specific platforms

The following example shows how the platform? method and an if statement can be used in a recipe along with the ruby_block resource to run certain blocks of Ruby code on certain platforms:

if platform?('ubuntu', 'debian', 'redhat', 'centos', 'fedora', 'scientific', 'amazon')
  ruby_block 'update-java-alternatives' do
    block do
      if platform?('ubuntu', 'debian') and version == 6
        run_context = Chef::RunContext.new(node, {})
        r = Chef::Resource::Execute.new('update-java-alternatives', run_context)
        r.command 'update-java-alternatives -s java-6-openjdk'
        r.returns [0,2]
        r.run_action(:create)
      else

        require 'fileutils'
        arch = node['kernel']['machine'] =~ /x86_64/ ? 'x86_64' : 'i386'
        Chef::Log.debug("glob is #{java_home_parent}/java*#{version}*openjdk*")
        jdk_home = Dir.glob("#{java_home_parent}/java*#{version}*openjdk{,[-\.]#{arch}}")[0]
        Chef::Log.debug("jdk_home is #{jdk_home}")

        if File.exist? java_home
          FileUtils.rm_f java_home
        end
        FileUtils.ln_sf jdk_home, java_home

        cmd = Chef::ShellOut.new(
              %Q[ update-alternatives --install /usr/bin/java java #{java_home}/bin/java 1;
              update-alternatives --set java #{java_home}/bin/java ]
              ).run_command
           unless cmd.exitstatus == 0 or cmd.exitstatus == 2
          Chef::Application.fatal!('Failed to update-alternatives for openjdk!')
        end
      end
    end
    action :nothing
  end
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

script resource

[edit on GitHub]

Use the script resource to execute scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby. 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 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.

This resource is the base resource for several other resources used for scripting on specific platforms. For more information about specific resources for specific platforms, see the following topics:

Changed in 12.19 to support windows alternate user identity in execute resources

Syntax

A script resource block typically executes scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby:

script 'extract_module' do
  interpreter "bash"
  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

  • interpreter specifies the command shell to use
  • cwd specifies the directory from which the command is run
  • code specifies the command to run

It is more common to use the script-based resource that is specific to the command shell. Chef has shell-specific resources for Bash, csh, Perl, Python, and Ruby.

The same command as above, but run using the bash resource:

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

The full syntax for all of the properties that are available to the script resource is:

script 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  interpreter                String
  notifies                   # see description
  path                       Array
  returns                    Integer, Array
  subscribes                 # see description
  timeout                    Integer, Float
  user                       String
  password                   String
  domain                     String
  umask                      String, Integer
  action                     Symbol # defaults to :run if not specified
end

where

  • script 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, interpreter, path, returns, 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

The script 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 attributes:

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 Type: String, Integer

The group name or group ID that must be changed before running a command.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

interpreter

Ruby Type: String

The script interpreter to use during code execution.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
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:

script 'mycommand' do
  environment 'PATH' => "/my/path/to/bin:#{ENV['PATH']}"
end
retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array | Default Value: 0

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.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: Integer, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

user

Ruby Type: String

The user name of the user identity with which to launch the new process. Default value: nil. The user name may optionally be specified 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 Type: 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 Type: 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 Type: 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

Guard Interpreter

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.

Example

For example, the following code block will ensure the command is evaluated using the default interpreter as identified by the chef-client:

resource 'name' do
  guard_interpreter :default
  # code
end

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

Run a script

script 'install_something' do
  interpreter 'bash'
  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

or something like:

bash 'openvpn-server-key' do
  environment('KEY_CN' => 'server')
  code <<-EOF
    openssl req -batch -days #{node['openvpn']['key']['expire']} \
      -nodes -new -newkey rsa:#{key_size} -keyout #{key_dir}/server.key \
      -out #{key_dir}/server.csr -extensions server \
      -config #{key_dir}/openssl.cnf
  EOF
  not_if { File.exist?('#{key_dir}/server.crt') }
end

where code contains the OpenSSL command to be run. The not_if property tells the chef-client not to run the command if the file already exists.

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

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
script 'mkdir test_dir' do
 interpreter "bash"
 code  "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username"
 password "password"
end

# Passing username and domain
script 'mkdir test_dir' do
 interpreter "bash"
 code  "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 domain "domain-name"
 user "username"
 password "password"
end

# Passing username = 'domain-name\\username'. No domain is passed
script 'mkdir test_dir' do
 interpreter "bash"
 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
script 'mkdir test_dir' do
 interpreter "bash"
 code  "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username@domain-name"
 password "password"
end

service resource

[edit on GitHub]

Use the service resource to manage a service.

Syntax

The service resource has the following syntax:

service "tomcat" do
  action :start
end

will start the Apache Tomcat service.

The full syntax for all of the properties that are available to the service resource is:

service 'name' do
  init_command               String
  notifies                   # see description
  options                    Array, String
  pattern                    String
  priority                   Integer, String, Hash
  reload_command             String
  restart_command            String
  service_name               String # defaults to 'name' if not specified
  start_command              String
  status_command             String
  stop_command               String
  subscribes                 # see description
  supports                   Hash
  timeout                    Integer # Microsoft Windows only
  action                     Symbol # defaults to :nothing if not specified
end

where

  • service is the resource
  • name is the name of the resource block; when the path property is not specified, name is also the path to the directory, from the root
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • init_command, options, pattern, priority, reload_command, restart_command, service_name, start_command, status_command, stop_command, supports, and timeout are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions

The service resource has the following actions:

:disable
Disable a service. This action is equivalent to a Disabled startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot.
:enable
Enable a service at boot. This action is equivalent to an Automatic startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot.
:nothing
Default. Do nothing with a service.
:reload
Reload the configuration for this service.
:restart
Restart a service.
:start
Start a service, and keep it running until stopped or disabled.
:stop
Stop a service.

Note

To manage a Microsoft Windows service with a Manual startup type, the windows_service resource must be used.

Properties

The service resource has the following properties:

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

init_command

Ruby Type: String

The path to the init script that is associated with the service. Use init_command to prevent the need to specify overrides for the start_command, stop_command, and restart_command properties. When this property is not specified, the chef-client will use the default init command for the service provider being used.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
options

Ruby Type: Array, String

Solaris platform only. Options to pass to the service command. See the svcadm manual for details of possible options.

pattern

Ruby Type: String | Default Value: service_name

The pattern to look for in the process table.

priority

Ruby Type: Integer, String, Hash

Debian platform only. The relative priority of the program for start and shutdown ordering. May be an integer or a Hash. An integer is used to define the start run levels; stop run levels are then 100-integer. A Hash is used to define values for specific run levels. For example, { 2 => [:start, 20], 3 => [:stop, 55] } will set a priority of twenty for run level two and a priority of fifty-five for run level three.

reload_command

Ruby Type: String

The command used to tell a service to reload its configuration.

restart_command

Ruby Type: String

The command used to restart a service.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

service_name

Ruby Type: String

The name of the service. Default value: the name of the resource block. See “Syntax” section above for more information.

start_command

Ruby Type: String

The command used to start a service.

status_command

Ruby Type: String

The command used to check the run status for a service.

stop_command

Ruby Type: String

The command used to stop a service.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
supports

Ruby Type: Hash

A list of properties that controls how the chef-client is to attempt to manage a service: :restart, :reload, :status. For :restart, the init script or other service provider can use a restart command; if :restart is not specified, the chef-client attempts to stop and then start a service. For :reload, the init script or other service provider can use a reload command. For :status, the init script or other service provider can use a status command to determine if the service is running; if :status is not specified, the chef-client attempts to match the service_name against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: { restart: false, reload: false, status: false } for all platforms (except for the Red Hat platform family, which defaults to { restart: false, reload: false, status: true }.)

timeout

Ruby Type: Integer | Default Value: 60

Microsoft Windows platform only. The amount of time (in seconds) to wait before timing out.

Examples

The following examples demonstrate various approaches for using resources in recipes. If you want to see examples of how Chef uses resources in recipes, take a closer look at the cookbooks that Chef authors and maintains: https://github.com/chef-cookbooks.

Start a service

service 'example_service' do
  action :start
end

Start a service, enable it

service 'example_service' do
  supports :status => true, :restart => true, :reload => true
  action [ :enable, :start ]
end

Use a pattern

service 'samba' do
  pattern 'smbd'
  action [:enable, :start]
end

Use the :nothing common action

service 'memcached' do
  action :nothing
end

Use the retries common attribute

service 'apache' do
  action [ :enable, :start ]
  retries 3
end

Manage a service, depending on the node platform

service 'example_service' do
  case node['platform']
  when 'centos','redhat','fedora'
    service_name 'redhat_name'
  else
    service_name 'other_name'
  end
  supports :restart => true
  action [ :enable, :start ]
end

Change a service provider, depending on the node platform

service 'example_service' do
  case node['platform']
  when 'ubuntu'
    if node['platform_version'].to_f >= 9.10
      provider Chef::Provider::Service::Upstart
    end
  end
  action [:enable, :start]
end

Reload a service using a template

To reload a service that is based on a template, use the template and service resources together in the same recipe, similar to the following:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
end

service 'apache' do
  action :enable
  subscribes :reload, 'template[/tmp/somefile]', :immediately
end

where the subscribes notification is used to reload the service whenever the template is modified.

Enable a service after a restart or reload

service 'apache' do
  supports :restart => true, :reload => true
  action :enable
end

Set an IP address using variables and a template

The following example shows how the template resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following:

default['nginx']['dir'] = '/etc/nginx'

The recipe then does the following to:

  • Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address
  • Use the service resource to restart and reload the Nginx service
  • Load a template named authorized_ip.erb from the /templates directory that is used to set the IP address values based on the variables specified in the recipe
node.default['nginx']['remote_ip_var'] = 'remote_addr'
node.default['nginx']['authorized_ips'] = ['127.0.0.1/32']

service 'nginx' do
  supports :status => true, :restart => true, :reload => true
end

template 'authorized_ip' do
  path "#{node['nginx']['dir']}/authorized_ip"
  source 'modules/authorized_ip.erb'
  owner 'root'
  group 'root'
  mode '0755'
  variables(
    :remote_ip_var => node['nginx']['remote_ip_var'],
    :authorized_ips => node['nginx']['authorized_ips']
  )

  notifies :reload, 'service[nginx]', :immediately
end

where the variables property tells the template to use the variables set at the beginning of the recipe and the source property is used to call a template file located in the cookbook’s /templates directory. The template file looks similar to:

geo $<%= @remote_ip_var %> $authorized_ip {
  default no;
  <% @authorized_ips.each do |ip| %>
  <%= "#{ip} yes;" %>
  <% end %>
}

Use a cron timer to manage a service

The following example shows how to install the crond application using two resources and a variable:

# the following code sample comes from the ``cron`` cookbook:
# https://github.com/chef-cookbooks/cron

cron_package = case node['platform']
  when 'redhat', 'centos', 'scientific', 'fedora', 'amazon'
    node['platform_version'].to_f >= 6.0 ? 'cronie' : 'vixie-cron'
  else
    'cron'
  end

package cron_package do
  action :install
end

service 'crond' do
  case node['platform']
  when 'redhat', 'centos', 'scientific', 'fedora', 'amazon'
    service_name 'crond'
  when 'debian', 'ubuntu', 'suse'
    service_name 'cron'
  end
  action [:start, :enable]
end

where

  • cron_package is a variable that is used to identify which platforms apply to which install packages
  • the package resource uses the cron_package variable to determine how to install the crond application on various nodes (with various platforms)
  • the service resource enables the crond application on nodes that have Red Hat, CentOS, Red Hat Enterprise Linux, Fedora, or Amazon Web Services (AWS), and the cron service on nodes that run Debian, Ubuntu, or openSUSE

Restart a service, and then notify a different service

The following example shows how start a service named example_service and immediately notify the Nginx service to restart.

service 'example_service' do
  action :start
  notifies :restart, 'service[nginx]', :immediately
end

Restart one service before restarting another

This example uses the :before notification to restart the php-fpm service before restarting nginx:

service 'nginx' do
  action :restart
  notifies :restart, 'service[php-fpm]', :before
end

With the :before notification, the action specified for the nginx resource will not run until action has been taken on the notified resource (php-fpm).

Stop a service, do stuff, and then restart it

The following example shows how to use the execute, service, and mount resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following:

  • Checks to see if the Amazon EC2 node has MySQL
  • If the node has MySQL, stops MySQL
  • Installs MySQL
  • Mounts the node
  • Restarts MySQL
# the following code sample comes from the ``server_ec2``
# recipe in the following cookbook:
# https://github.com/chef-cookbooks/mysql

if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path']))

  service 'mysql' do
    action :stop
  end

  execute 'install-mysql' do
    command "mv #{node['mysql']['data_dir']} #{node['mysql']['ec2_path']}"
    not_if do FileTest.directory?(node['mysql']['ec2_path']) end
  end

  [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir|
    directory dir do
      owner 'mysql'
      group 'mysql'
    end
  end

  mount node['mysql']['data_dir'] do
    device node['mysql']['ec2_path']
    fstype 'none'
    options 'bind,rw'
    action [:mount, :enable]
  end

  service 'mysql' do
    action :start
  end

end

where

  • the two service resources are used to stop, and then restart the MySQL service
  • the execute resource is used to install MySQL
  • the mount resource is used to mount the node and enable MySQL

Control a service using the execute resource

Warning

This is an example of something that should NOT be done. Use the service resource to control a service, not the execute resource.

Do something like this:

service 'tomcat' do
  action :start
end

and NOT something like this:

execute 'start-tomcat' do
  command '/etc/init.d/tomcat6 start'
  action :run
end

There is no reason to use the execute resource to control a service because the service resource exposes the start_command property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner.

Enable a service on AIX using the mkitab command

The service resource does not support using the :enable and :disable actions with resources that are managed using System Resource Controller (SRC). This is because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot.

One approach for enabling or disabling services that are managed by System Resource Controller (SRC) is to use the execute resource to invoke mkitab, and then use that command to enable or disable the service.

The following example shows how to install a service:

execute "install #{node['chef_client']['svc_name']} in SRC" do
  command "mkssys -s #{node['chef_client']['svc_name']}
                  -p #{node['chef_client']['bin']}
                  -u root
                  -S
                  -n 15
                  -f 9
                  -o #{node['chef_client']['log_dir']}/client.log
                  -e #{node['chef_client']['log_dir']}/client.log -a '
                  -i #{node['chef_client']['interval']}
                  -s #{node['chef_client']['splay']}'"
  not_if "lssrc -s #{node['chef_client']['svc_name']}"
  action :run
end

and then enable it using the mkitab command:

execute "enable #{node['chef_client']['svc_name']}" do
  command "mkitab '#{node['chef_client']['svc_name']}:2:once:/usr/bin/startsrc
                  -s #{node['chef_client']['svc_name']} > /dev/console 2>&1'"
  not_if "lsitab #{node['chef_client']['svc_name']}"
end

smartos_package resource

[edit on GitHub]

Use the smartos_package resource to manage packages for the SmartOS 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 smartos_package resource block manages a package on a node, typically by installing it. The simplest use of the smartos_package resource is:

smartos_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 smartos_package resource is:

smartos_package 'name' do
  options                      String, Array
  package_name                 String, Array
  response_file                String
  response_file_variables      Hash
  source                       String
  timeout                      String, Integer
  version                      String, Array
  action                       Symbol # defaults to :install if not specified
end

where:

  • smartos_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • options, package_name, response_file, response_file_variables, source, timeout, and version are the properties available to this resource.

Actions

The smartos_package 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.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties

The smartos_package resource has the following properties:

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
options

Ruby Type: String

One (or more) additional options that are passed to the command.

package_name

Ruby Type: String, Array

The name of the package. Default value: the name of the resource block. See “Syntax” section above for more information.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

smartos_package 'name of package' do
  action :install
end

solaris_package resource

[edit on GitHub]

The solaris_package resource is used to manage packages for the Solaris 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 solaris_package resource block manages a package on a node, typically by installing it. The simplest use of the solaris_package resource is:

solaris_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 solaris_package resource is:

solaris_package 'name' do
  options                      String, Array
  package_name                 String, Array
  response_file                String
  response_file_variables      Hash
  source                       String
  timeout                      String, Integer
  version                      String, Array
  action                       Symbol # defaults to :install if not specified
end

where:

  • solaris_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • options, package_name, response_file, response_file_variables, source, timeout, and version are the properties available to this resource.

Actions

The solaris_package 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

The solaris_package resource has the following properties:

source

Ruby Type: String

Required. The path to a package in the local file system.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
options

Ruby Type: String

One (or more) additional options that are passed to the command.

package_name

Ruby Type: String, Array

The name of the package. Default value: the name of the resource block. See “Syntax” section above for more information.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

solaris_package 'name of package' do
  source '/packages_directory'
  action :install
end

ssh_known_hosts_entry resource

[edit on GitHub]

Use the ssh_known_hosts_entry resource to add an entry for the specified host in /etc/ssh/ssh_known_hosts or a user’s known hosts file if specified.

New in Chef Client 14.3.

Syntax

The ssh_known_hosts_entry resource has the following syntax:

ssh_known_hosts_entry 'name' do
  file_location      String # default value: /etc/ssh/ssh_known_hosts
  group              String
  hash_entries       true, false # default value: false
  host               String # default value: 'name' unless specified
  key                String
  key_type           String # default value: rsa
  mode               String # default value: 0644
  owner              String # default value: root
  port               Integer # default value: 22
  timeout            Integer # default value: 30
  action             Symbol # defaults to :create if not specified
end

where:

  • ssh_known_hosts_entry is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • file_location, group, hash_entries, host, key, key_type, mode, owner, port, and timeout are the properties available to this resource.

Actions

The ssh_known_hosts_entry resource has the following actions:

:create
Default. Create an entry in the ssh_known_hosts file.
:flush
Immediately flush the entries to the config file. Without this the actual writing of the file is delayed in the Chef run so all entries can be accumulated before writing the file out.
: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

The ssh_known_hosts_entry resource has the following properties:

file_location

Ruby Type: String | Default Value: /etc/ssh/ssh_known_hosts

The location of the ssh known hosts file. Change this to set a known host file for a particular user.

group

Ruby Type: String

The file group for the ssh_known_hosts file.

hash_entries

Ruby Type: true, false | Default Value: false

Hash the hostname and addresses in the ssh_known_hosts file for privacy.

host

Ruby Type: String | Default Value: 'name'

The host to add to the known hosts file.

key

Ruby Type: String

An optional key for the host. If not provided this will be automatically determined.

key_type

Ruby Type: String | Default Value: rsa

The type of key to store.

mode

Ruby Type: String | Default Value: 0644

The file mode for the ssh_known_hosts file.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
owner

Ruby Type: String | Default Value: root

The file owner for the ssh_known_hosts file.

port

Ruby Type: Integer | Default Value: 22

The server port that the ssh-keyscan command will use to gather the public key.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: Integer | Default Value: 30

The timeout in seconds for ssh-keyscan.

subversion resource

[edit on GitHub]

Use the subversion resource to manage source control resources that exist in a Subversion repository.

Warning

The subversion resource has known bugs and may not work as expected. For more information see Chef GitHub issues, particularly #4050 and #4257.

Syntax

The subversion resource has the following syntax:

subversion 'name' do
  checkout_branch        String # default value: deploy
  depth                  Integer
  destination            String # default value: 'name' unless specified
  enable_checkout        true, false # default value: true
  enable_submodules      true, false # default value: false
  environment            Hash, nil
  group                  String, Integer
  remote                 String # default value: origin
  repository             String
  revision               String # default value: HEAD
  ssh_wrapper            String
  svn_arguments          String, nil, false # default value: --no-auth-cache
  svn_binary             String
  svn_info_args          String, nil, false # default value: --no-auth-cache
  svn_password           String
  svn_username           String
  timeout                Integer
  user                   String, Integer
  action                 Symbol # defaults to :sync if not specified
end

where:

  • subversion is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • checkout_branch, depth, destination, enable_checkout, enable_submodules, environment, group, remote, repository, revision, ssh_wrapper, svn_arguments, svn_binary, svn_info_args, svn_password, svn_username, timeout, and user are the properties available to this resource.

Actions

The subversion resource has the following actions:

:checkout
Clone or check out the source. When a checkout is available, this provider does nothing.
:export
Export the source, excluding or removing any version control artifacts.
:force_export
Export the source, excluding or removing any version control artifacts and force an export of the source that is overwriting the existing copy (if it exists).
: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.
:sync
Default. Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes.

Properties

The subversion resource has the following properties:

destination

Ruby Type: String

The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block. See “Syntax” section above for more information.

group

Ruby Type: String, Integer

The system group that is responsible for the checked-out code.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
repository

Ruby Type: String

The URI for the Subversion repository.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

revision

Ruby Type: String | Default Value: HEAD

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.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
svn_arguments

Ruby Type: String

The extra arguments that are passed to the Subversion command.

svn_info_args

Ruby Type: String

Use when the svn info command is used by the chef-client and arguments need to be passed. The svn_arguments command does not work when the svn info command is used.

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.

timeout

Ruby Type: Integer

The amount of time (in seconds) to wait for a command to execute before timing out. When this property is specified using the deploy resource, the value of the timeout property is passed from the deploy resource to the subversion resource.

user

Ruby Type: String, Integer

The system user that is responsible for the checked-out code.

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.

Get the latest version of an application

subversion 'CouchDB Edge' do
  repository 'http://svn.apache.org/repos/asf/couchdb/trunk'
  revision 'HEAD'
  destination '/opt/mysources/couch'
  action :sync
end

sudo resource

[edit on GitHub]

Use the sudo resource to add or remove individual sudo entries using sudoers.d files. Sudo version 1.7.2 or newer is required to use the sudo resource, as it relies on the #includedir directive introduced in version 1.7.2. This resource does not enforce installation of the required sudo version. Chef-supported releases of Ubuntu, Debian and RHEL (6+) all support this feature.

New in Chef Client 14.0.

Syntax

The sudo resource has the following syntax:

sudo 'name' do
  command_aliases        Array
  commands               Array # default value: ["ALL"]
  config_prefix          String
  defaults               Array
  env_keep_add           Array
  env_keep_subtract      Array
  filename               String # default value: 'name' unless specified
  groups                 String, Array
  host                   String # default value: ALL
  noexec                 true, false # default value: false
  nopasswd               true, false # default value: false
  runas                  String # default value: ALL
  setenv                 true, false # default value: false
  template               String
  users                  String, Array
  variables              Hash, nil
  visudo_binary          String # default value: /usr/sbin/visudo
  visudo_path            String
  action                 Symbol # defaults to :create if not specified
end

where:

  • sudo is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • command_aliases, commands, config_prefix, defaults, env_keep_add, env_keep_subtract, filename, groups, host, noexec, nopasswd, runas, setenv, template, users, variables, visudo_binary, and visudo_path are the properties available to this resource.

Actions

The sudo resource has the following actions:

:create
Default. Create a single sudoers configuration file in the sudoers.d directory.
:delete
Removed a sudoers configuration file from the sudoers.d 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

The sudo resource has the following properties:

command_aliases

Ruby Type: Array

Command aliases that can be used as allowed commands later in the configuration.

commands

Ruby Type: Array | Default Value: ["ALL"]

An array of commands this sudoer can execute.

config_prefix

Ruby Type: String | Default Value: Prefix values based on the node's platform

The directory that contains the sudoers configuration file.

defaults

Ruby Type: Array

An array of defaults for the user/group.

env_keep_add

Ruby Type: Array

An array of strings to add to env_keep.

env_keep_subtract

Ruby Type: Array

An array of strings to remove from env_keep.

filename

Ruby Type: String | Default Value: 'name'

Optional. The name of the sudoers.d file, if it differs from the name of the resource block.

groups

Ruby Type: String, Array | Default Value: []

Group(s) to provide sudo privileges to. This accepts either an array or a comma-separated list. Leading % on group names is optional.

host

Ruby Type: String| Default Value: "ALL"

The host to set in the sudo configuration.

noexec

Ruby Type: true, false | Default Value: false

Prevent commands from shelling out.

nopasswd

Ruby Type: true, false | Default Value: false

Allow sudo to be run without specifying a password.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
runas

Ruby Type: String | Default Value: "ALL"

User that the command(s) can be run as.

setenv

Ruby Type: true, false | Default Value: false

Determines whether or not to permit preservation of the environment with sudo -E.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
template

Ruby Type: String

The name of the .erb template in your cookbook, if you wish to supply your own template.

users

Ruby Type: String, Array | Default Value: []

User(s) to provide sudo privileges to. This property accepts either an array or a comma-separated list.

variables

Ruby Type: Hash, nil | Default Value: nil

The variables to pass to the custom template. This property is ignored if not using a custom template.

visudo_binary

Ruby Type: String | Default Value: /usr/sbin/visudo

The path to visudo for configuration verification.

Examples

Grant a user sudo privileges for any command

sudo 'admin' do
  user 'admin'
end

Grant a user and groups sudo privileges for any command

sudo 'admins' do
  users 'bob'
  groups 'sysadmins, superusers'
end

Grant passwordless sudo privileges for specific commands

sudo 'passwordless-access' do
  commands ['systemctl restart httpd', 'systemctl restart mysql']
  nopasswd true
end

swap_file resource

[edit on GitHub]

Use the swap_file resource to create or delete swap files on Linux systems, and optionally to manage the swappiness configuration for a host.

New in Chef Client 14.0.

Syntax

The swap_file resource has the following syntax:

swap_file 'name' do
  path            String # default value: 'name' unless specified
  persist         true, false # default value: false
  size            Integer
  swappiness      Integer
  timeout         Integer # default value: 600
  action          Symbol # defaults to :create if not specified
end

where:

  • swap_file is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • path, persist, size, swappiness, and timeout are the properties available to this resource.

Actions

The swap_file resource has the following actions:

:create
Default. Create a swap file.
:remove
Remove a swap file and disable swap.
: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

The swap_file resource has the following properties:

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
path

Ruby Type: String | Default Value: 'name'

The path where the swap file will be created on the system, if it differs from the resource block name.

persist

Ruby Type: true, false | Default Value: false

Persist the swapon.

size

Ruby Type: Integer

The size (in MBs) of the swap file.

swappiness

Ruby Type: Integer

The swappiness value to set on the system.

timeout

Ruby Type: Integer | Default Value: 600

Timeout for dd / fallocate commands.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples

Create a swap file

swap_file '/dev/sda1' do
  size 1024
end

Remove a swap file

swap_file '/dev/sda1' do
  action :remove
end

sysctl resource

[edit on GitHub]

Use the sysctl resource to set or remove kernel parameters using the sysctl command line tool and configuration files in the system’s sysctl.d directory. Configuration files managed by this resource are named 99-chef-KEYNAME.conf. If an existing value was already set, it will be backed up to the node and restored if the :remove action is used later.

New in Chef Client 14.0.

Syntax

The sysctl resource has the following syntax:

sysctl 'name' do
  conf_dir          String # default value: /etc/sysctl.d
  ignore_error      true, false # default value: false
  key               String # default value: 'name' unless specified
  value             Array, String, Integer, Float
  action            Symbol # defaults to :apply if not specified
end

where:

  • sysctl is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • conf_dir, ignore_error, key, and value are the properties available to this resource.

Actions

The sysctl resource has the following actions:

:apply
Default. Set the kernel parameter and update the sysctl settings.
:remove
Remove the kernel parameter and update the sysctl settings.
: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

The sysctl resource has the following properties:

conf_dir

Ruby Type: String | Default Value: /etc/sysctl.d

The configuration directory to write the config to.

ignore_error

Ruby Type: true, false | Default Value: false

Ignore any errors when setting the value on the command line.

key

Ruby Type: String | Default Value: 'name'

The kernel parameter key in dotted format, if it differs from the resource block name.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
value

Ruby Type: Array, String, Integer, Float

Required. The value to set.

systemd_unit resource

[edit on GitHub]

Use the systemd_unit resource to create, manage, and run systemd units.

New in Chef Client 12.11.

Syntax

The systemd_unit resource has the following syntax:

systemd_unit 'sysstat-collect.timer' do
  content <<-EOU.gsub(/^\s+/, '')
  [Unit]
  Description=Run system activity accounting tool every 10 minutes

  [Timer]
  OnCalendar=*:00/10

  [Install]
  WantedBy=sysstat.service
  EOU

  action [:create, :enable]
end

The full syntax for all of the properties that are available to the systemd_unit resource is:

systemd_unit 'name.service' do
  content                String or Hash
  user                   String
  triggers_reload        Boolean
end

where:

  • systemd_unit is the resource.
  • name is the name of the unit. Must include the type/suffix (e.g. name.socket or name.service).
  • user is the user account that systemd units run under. If not specified, systemd units will run under the system account.
  • content describes the behavior of the unit

Actions

The systemd_unit resource has the following actions:

:create
Create a unit file, if it does not already exist.
:delete
Delete a unit file, if it exists.
:enable
Ensure the unit will be started after the next system boot.
:disable
Ensure the unit will not be started after the next system boot.
:nothing
Default. Do nothing with the unit.
:mask
Ensure the unit will not start, even to satisfy dependencies.
:unmask
Stop the unit from being masked and cause it to start as specified.
:preset

Restore the preset “enable/disable” configuration for a unit.

New in Chef Client 14.0.

:reenable

Reenable a unit file.

New in Chef Client 14.0.

:revert

Revet to a vendor’s version of a unit file.

New in Chef Client 14.0.

:start
Start a unit based in its systemd unit file.
:stop
Stop a running unit.
:restart
Restart a unit.
:reload
Reload the configuration file for a unit.
:try_restart
Try to restart a unit if the unit is running.
:reload_or_restart
For units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will restart the service so the new configuration is applied.
:reload_or_try_restart
For units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will try to restart the service so the new configuration is applied.

Properties

The systemd_unit resource has the following properties:

user

Ruby Type: String

The user account that the systemd unit process is run under. The path to the unit for that user would be something like /etc/systemd/user/sshd.service. If no user account is specified, the systemd unit will run under a system account, with the path to the unit being something like /etc/systemd/system/sshd.service.

content

Ruby Type: String, Hash

A string or hash that contains a systemd unit file definition that describes the properties of systemd-managed entities, such as services, sockets, devices, and so on. In Chef 14.4, repeatable options can be implemented with an array.

triggers_reload

Ruby Type: true, false | Default Value: true

Specifies whether to trigger a daemon reload when creating or deleting a unit.

verify

Ruby Type: true, false

Specifies if the unit will be verified before installation. Systemd can be overly strict when verifying units, so in certain cases it is preferable not to verify the unit. Defaults to true.

Examples

Create etcd systemd service unit file

systemd_unit 'etcd.service' do
  content({Unit: {
            Description: 'Etcd',
            Documentation: ['https://coreos.com/etcd', 'man:etcd(1)'],
            After: 'network.target',
          },
          Service: {
            Type: 'notify',
            ExecStart: '/usr/local/etcd',
            Restart: 'always',
          },
          Install: {
            WantedBy: 'multi-user.target',
          }})
  action :create
end

template resource

[edit on GitHub]

A cookbook template is an Embedded Ruby (ERB) template that is used to dynamically generate static text files. Templates may contain Ruby expressions and statements, and are a great way to manage configuration files. Use the template resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template file in a cookbook’s /templates directory.

Note

The Chef Client uses Erubis for templates, which is a fast, secure, and extensible implementation of embedded Ruby. Erubis should be familiar to members of the Ruby on Rails, Merb, or Puppet communities. For more information about Erubis, see: http://www.kuwata-lab.com/erubis/.

Use the template resource to manage the contents of a file using an Embedded Ruby (ERB) template by transferring files from a sub-directory of COOKBOOK_NAME/templates/ to a specified path located on a host that is running the chef-client. This resource includes actions and properties from the file resource. Template files managed by the template resource follow the same file specificity rules as the remote_file and file resources.

Syntax

A template resource block typically declares the location in which a file is to be created, the source template that will be used to create the file, and the permissions needed on that file. For example:

template '/etc/motd' do
  source 'motd.erb'
  owner 'root'
  group 'root'
  mode '0755'
end

where

  • '/etc/motd' specifies the location in which the file is created
  • 'motd.erb' specifies the name of a template that exists in in the /templates folder of a cookbook
  • owner, group, and mode define the permissions

The full syntax for all of the properties that are available to the template resource is:

template 'name' do
  atomic_update              true, false
  backup                     false, Integer
  cookbook                   String
  force_unlink               true, false
  group                      String, Integer
  helper(:method)            Method { String } # see Helpers below
  helpers(module)            Module # see Helpers below
  inherits                   true, false
  local                      true, false
  manage_symlink_source      true, false
  mode                       String, Integer
  notifies                   # see description
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  rights                     Hash
  sensitive                  true, false
  source                     String, Array
  subscribes                 # see description
  variables                  Hash
  verify                     String, Block
  action                     Symbol # defaults to :create if not specified
end

where

  • template is the resource
  • name is the name of the resource block, typically the path to the location in which a file is created and also the name of the file to be managed. For example: /var/www/html/index.html, where /var/www/html/ is the fully qualified path to the location and index.html is the name of the file
  • source is the template file that will be used to create the file on the node, for example: index.html.erb; the template file is located in the /templates directory of a cookbook
  • action identifies the steps the chef-client will take to bring the node into the desired state
  • atomic_update, backup, cookbook, force_unlink, group, helper, helpers, inherits, local, manage_symlink_source, mode, owner, path, rights, sensitive, source, variables, 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 Type: true, false | Default Value: true

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.

backup

Ruby Type: false, Integer | Default Value: 5

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.

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 Type: true, false | Default Value: false

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.

group

Ruby Type: 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).

helper

Ruby Type: Method | Default Value: {}

Define a helper method inline. For example: helper(:hello_world) { "hello world" } or helper(:app) { node["app"] } or helper(:app_conf) { |setting| node["app"][setting] }.

helpers

Ruby Type: Module | Default Value: []

Define a helper module inline or in a library. For example, an inline module: helpers do, which is then followed by a block of Ruby code. And for a library module: helpers(MyHelperModule).

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

inherits

Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

local

Ruby Type: true, false | Default Value: false

Load a template from a local path. By default, the chef-client loads templates from a cookbook’s /templates directory. When this property is set to true, use the source property to specify the path to a template on the local node.

manage_symlink_source

Ruby Type: true, false | Default Value: true (with warning)

Change the behavior of the file resource if it is pointed at a symlink. When this value is set to true, the Chef client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to false, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file.

The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning.

mode

Ruby Type: 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 notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
owner

Ruby Type: 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.

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.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

rights

Ruby Type: 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 Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by the chef-client.

source

Ruby Type: String, Array

The location of a template file. By default, the chef-client looks for a template file in the /templates directory of a cookbook. When the local property is set to true, use to specify the path to a template on the local node. This property may also be used to distribute specific files to specific platforms. See “File Specificity” below for more information. Default value: the name of the resource block. 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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
variables

Ruby Type: Hash

A Hash of variables that are passed into a Ruby template file.

The variables property of the template resource can be used to reference a partial template file by using a Hash. For example:

template '/file/name.txt' do
  variables partials: {
    'partial_name_1.txt.erb' => 'message',
    'partial_name_2.txt.erb' => 'message',
    'partial_name_3.txt.erb' => 'message',
  }
end

where each of the partial template files can then be combined using normal Ruby template patterns within a template file, such as:

<% @partials.each do |partial, message| %>
  Here is <%= partial %>
  <%= render partial, :variables => {:message => message} %>
<% end %>
verify

Ruby Type: 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:

template '/tmp/baz' do
  verify { 1 == 1 }
end

This should return true:

template '/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:

template '/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:

template '/tmp/bar' do
  verify { 1 == 1}
end

And this should return true:

template '/tmp/foo' do
  verify do |path|
    true
  end
end

Whereas, this should return false:

template '/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.

Using Templates

To use a template, two things must happen:

  1. A template resource must be added to a recipe
  2. An Embedded Ruby (ERB) template must be added to a cookbook

For example, the following template file and template resource settings can be used to manage a configuration file named /etc/sudoers. Within a cookbook that uses sudo, the following resource could be added to /recipes/default.rb:

template '/etc/sudoers' do
  source 'sudoers.erb'
  mode '0440'
  owner 'root'
  group 'root'
  variables(sudoers_groups: node['authorization']['sudo']['groups'],
            sudoers_users: node['authorization']['sudo']['users'])
end

And then create a template called sudoers.erb and save it to templates/default/sudoers.erb:

#
# /etc/sudoers
#
# Generated by Chef for <%= node['fqdn'] %>
#

Defaults        !lecture,tty_tickets,!fqdn

# User privilege specification
root          ALL=(ALL) ALL

<% @sudoers_users.each do |user| -%>
<%= user %>   ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL
<% end -%>

# Members of the sysadmin group may gain root privileges
%sysadmin     ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL

<% @sudoers_groups.each do |group| -%>
# Members of the group '<%= group %>' may gain root privileges
<%= group %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL
<% end -%>

And then set the default attributes in attributes/default.rb:

default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin)
default['authorization']['sudo']['users'] = %w(jerry greg)

File Specificity

A cookbook is frequently designed to work across many platforms and is often required to distribute a specific template to a specific platform. A cookbook can be designed to support the distribution of templates across platforms, while ensuring that the correct template ends up on each system.

The pattern for template specificity depends on two things: the lookup path and the source. 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 property to define an explicit lookup path. For example:

template '/test' do
  source ["#{node.chef_environment}.erb", 'default.erb']
end

The following example emulates the entire file specificity pattern by defining it as an explicit path:

template '/test' do
  source %W(
    host-#{node['fqdn']}/test.erb
    #{node['platform']}-#{node['platform_version']}/test.erb
    #{node['platform']}/test.erb
    default/test.erb
  )
end

A cookbook may have a /templates directory structure like this:

/templates/
  windows-6.2
  windows-6.1
  windows-6.0
  windows
  default

and a resource that looks something like the following:

template 'C:\path\to\file\text_file.txt' do
  source 'text_file.txt'
  mode '0755'
  owner 'root'
  group 'root'
end

This resource would be matched in the same order as the /templates directory structure. For a node named host-node-desktop that is running Windows 7, the second item would be the matching item and the location:

/templates
  windows-6.2/text_file.txt
  windows-6.1/text_file.txt
  windows-6.0/text_file.txt
  windows/text_file.txt
  default/text_file.txt

Helpers

A helper is a method or a module that can be used to extend a template. There are three approaches:

  • An inline helper method
  • An inline helper module
  • A cookbook library module

Use the helper attribute in a recipe to define an inline helper method. Use the helpers attribute to define an inline helper module or a cookbook library module.

Inline Methods

A template helper method is always defined inline on a per-resource basis. A simple example:

template '/path' do
  helper(:hello_world) { 'hello world' }
end

Another way to define an inline helper method is to reference a node object so that repeated calls to one (or more) cookbook attributes can be done efficiently:

template '/path' do
  helper(:app) { node['app'] }
end

An inline helper method can also take arguments:

template '/path' do
  helper(:app_conf) { |setting| node['app'][setting] }
end

Once declared, a template can then use the helper methods to build a file. For example:

Say hello: <%= hello_world %>

or:

node['app']['listen_port'] is: <%= app['listen_port'] %>

or:

node['app']['log_location'] is: <%= app_conf('log_location') %>
Inline Modules

A template helper module can be defined inline on a per-resource basis. This approach can be useful when a template requires more complex information. For example:

template '/path' do
  helpers do

    def hello_world
      'hello world'
    end

    def app
      node['app']
    end

    def app_conf(setting)
      node['app']['setting']
    end

  end
end

where the hello_world, app, and app_conf(setting) methods comprise the module that extends a template.

Library Modules

A template helper module can be defined in a library. This is useful when extensions need to be reused across recipes or to make it easier to manage code that would otherwise be defined inline on a per-recipe basis.

template '/path/to/template.erb' do
  helpers(MyHelperModule)
end

Host Notation

The naming of folders within cookbook directories must literally match the host notation used for template specificity matching. For example, if a host is named foo.example.com, then the folder must be named host-foo.example.com.

Partial Templates

A template can be built in a way that allows it to contain references to one (or more) smaller template files. (These smaller template files are also referred to as partials.) A partial can be referenced from a template file in one of the following ways:

  • By using the render method in the template file
  • By using the template resource and the variables property.
render Method

Use the render method in a template to reference a partial template file:

<%= render "partial_name.txt.erb", :option => {} %>

where partial_name is the name of the partial template file and :option is one (or more) of the following:

Option Description
:cookbook By default, a partial template file is assumed to be located in the cookbook that contains the top-level template. Use this option to specify the path to a different cookbook
:local Indicates that the name of the partial template file should be interpreted as a path to a file in the local file system or looked up in a cookbook using the normal rules for template files. Set to true to interpret as a path to a file in the local file system and to false to use the normal rules for template files
:source By default, a partial template file is identified by its file name. Use this option to specify a different name or a local path to use (instead of the name of the partial template file)
:variables A hash of variable_name => value that will be made available to the partial template file. When this option is used, any variables that are defined in the top-level template that are required by the partial template file must have them defined explicitly using this option

For example:

<%= render "simple.txt.erb", :variables => {:user => Etc.getlogin }, :local => true %>

Transfer Frequency

The Chef Client caches a template when it is first requested. On each subsequent request for that template, the Chef Client compares that request to the template located on the Chef server. If the templates are the same, no transfer occurs.

Variables

An Embedded Ruby (ERB) template allows Ruby code to be embedded inside a text file within specially formatted tags. Ruby code can be embedded using expressions and statements. An expression is delimited by <%= and %>. For example:

<%= "my name is #{$ruby}" %>

A statement is delimited by a modifier, such as if, elseif, and else. For example:

if false
# this won't happen
elsif nil
      # this won't either
    end

Using a Ruby expression is the most common approach for defining template variables because this is how all variables that are sent to a template are referenced. Whenever a template needs to use an each, if, or end, use a Ruby statement.

When a template is rendered, Ruby expressions and statements are evaluated by the Chef Client. The variables listed in the template resource’s variables parameter and in the node object are evaluated. The Chef Client then passes these variables to the template, where they will be accessible as instance variables within the template. The node object can be accessed just as if it were part of a recipe, using the same syntax.

For example, a simple template resource like this:

node['fqdn'] = 'latte'
template '/tmp/foo' do
  source 'foo.erb'
  variables(x_men: 'are keen')
end

And a simple Embedded Ruby (ERB) template like this:

The node <%= node[:fqdn] %> thinks the x-men <%= @x_men %>

Would render something like:

The node latte thinks the x-men are keen

Even though this is a very simple example, the full capabilities of Ruby can be used to tackle even the most complex and demanding template requirements.

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.

Configure a file from a template

template '/tmp/config.conf' do
  source 'config.conf.erb'
end

Configure a file from a local template

template '/tmp/config.conf' do
  local true
  source '/tmp/config.conf.erb'
end

Configure a file using a variable map

template '/tmp/config.conf' do
  source 'config.conf.erb'
  variables(
    :config_var => node['configs']['config_var']
  )
end

Use the not_if condition

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

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

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

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

Use the only_if condition

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

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

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

Use a whitespace array (%w)

The following example shows how to use a Ruby whitespace array to define a list of configuration tools, and then use that list of tools within the template resource to ensure that all of these configuration tools are using the same RSA key:

%w{openssl.cnf pkitool vars Rakefile}.each do |f|
  template "/etc/openvpn/easy-rsa/#{f}" do
    source "#{f}.erb"
    owner 'root'
    group 'root'
    mode '0755'
  end
end

Use a relative path

template "#{ENV['HOME']}/chef-getting-started.txt" do
  source 'chef-getting-started.txt.erb'
  mode '0755'
end

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

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.

Set an IP address using variables and a template

The following example shows how the template resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following:

default['nginx']['dir'] = '/etc/nginx'

The recipe then does the following to:

  • Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address
  • Use the service resource to restart and reload the Nginx service
  • Load a template named authorized_ip.erb from the /templates directory that is used to set the IP address values based on the variables specified in the recipe
node.default['nginx']['remote_ip_var'] = 'remote_addr'
node.default['nginx']['authorized_ips'] = ['127.0.0.1/32']

service 'nginx' do
  supports :status => true, :restart => true, :reload => true
end

template 'authorized_ip' do
  path "#{node['nginx']['dir']}/authorized_ip"
  source 'modules/authorized_ip.erb'
  owner 'root'
  group 'root'
  mode '0755'
  variables(
    :remote_ip_var => node['nginx']['remote_ip_var'],
    :authorized_ips => node['nginx']['authorized_ips']
  )

  notifies :reload, 'service[nginx]', :immediately
end

where the variables property tells the template to use the variables set at the beginning of the recipe and the source property is used to call a template file located in the cookbook’s /templates directory. The template file looks similar to:

geo $<%= @remote_ip_var %> $authorized_ip {
  default no;
  <% @authorized_ips.each do |ip| %>
  <%= "#{ip} yes;" %>
  <% end %>
}

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.

Apply proxy settings consistently across a Chef organization

The following example shows how a template can be used to apply consistent proxy settings for all nodes of the same type:

template "#{node[:matching_node][:dir]}/sites-available/site_proxy.conf" do
  source 'site_proxy.matching_node.conf.erb'
  owner 'root'
  group 'root'
  mode '0755'
  variables(
    :ssl_certificate =>    "#{node[:matching_node][:dir]}/shared/certificates/site_proxy.crt",
    :ssl_key =>            "#{node[:matching_node][:dir]}/shared/certificates/site_proxy.key",
    :listen_port =>        node[:site][:matching_node_proxy][:listen_port],
    :server_name =>        node[:site][:matching_node_proxy][:server_name],
    :fqdn =>               node[:fqdn],
    :server_options =>     node[:site][:matching_node][:server][:options],
    :proxy_options =>      node[:site][:matching_node][:proxy][:options]
  )
end

where matching_node represents a type of node (like Nginx) and site_proxy represents the type of proxy being used for that type of node (like Nexus).

Get template settings from a local file

The template resource can be used to render a template based on settings contained in a local file on disk or to get the settings from a template in a cookbook. Most of the time, the settings are retrieved from a template in a cookbook. The following example shows how the template resource can be used to retrieve these settings from a local file.

The following example is based on a few assumptions:

  • The environment is a Ruby on Rails application that needs render a file named database.yml
  • Information about the application—the user, their password, the server—is stored in a data bag on the Chef server
  • The application is already deployed to the system and that only requirement in this example is to render the database.yml file

The application source tree looks something like:

myapp/
-> config/
   -> database.yml.erb

Note

There should not be a file named database.yml (without the .erb), as the database.yml file is what will be rendered using the template resource.

The deployment of the app will end up in /srv, so the full path to this template would be something like /srv/myapp/current/config/database.yml.erb.

The content of the template itself may look like this:

<%= @rails_env %>:
   adapter: <%= @adapter %>
   host: <%= @host %>
   database: <%= @database %>
   username: <%= @username %>
   password: <%= @password %>
   encoding: 'utf8'
   reconnect: true

The recipe will be similar to the following:

results = search(:node, "role:myapp_database_master AND chef_environment:#{node.chef_environment}")
db_master = results[0]

template '/srv/myapp/shared/database.yml' do
  source '/srv/myapp/current/config/database.yml.erb'
  local true
  variables(
    :rails_env => node.chef_environment,
    :adapter => db_master['myapp']['db_adapter'],
    :host => db_master['fqdn'],
    :database => "myapp_#{node.chef_environment}",
    :username => "myapp",
    :password => "SUPERSECRET",
  )
end

where:

  • the search method in the Recipe DSL is used to find the first node that is the database master (of which there should only be one)
  • the :adapter variable property may also require an attribute to have been set on a role, which then determines the correct adapter

The template will render similar to the following:

production:
  adapter: mysql
  host: domU-12-31-39-14-F1-C3.compute-1.internal
  database: myapp_production
  username: myapp
  password: SUPERSECRET
  encoding: utf8
  reconnect: true

This example showed how to use the template resource to render a template based on settings contained in a local file. Some other issues that should be considered when using this type of approach include:

  • Should the database.yml file be in a .gitignore file?
  • How do developers run the application locally?
  • Does this work with chef-solo?

Pass values from recipe to template

The following example shows how pass a value to a template using the variables property in the template resource. The template file is similar to:

[tcpout]
defaultGroup = splunk_indexers_<%= node['splunk']['receiver_port'] %>
disabled=false

[tcpout:splunk_indexers_<%= node['splunk']['receiver_port'] %>]
server=<% @splunk_servers.map do |s| -%><%= s['ipaddress'] %>:<%= s['splunk']['receiver_port'] %> <% end.join(', ') -%>
<% @outputs_conf.each_pair do |name, value| -%>
<%= name %> = <%= value %>
<% end -%>

The recipe then uses the variables attribute to find the values for splunk_servers and outputs_conf, before passing them into the template:

template "#{splunk_dir}/etc/system/local/outputs.conf" do
  source 'outputs.conf.erb'
  mode '0755'
  variables :splunk_servers => splunk_servers, :outputs_conf => node['splunk']['outputs_conf']
  notifies :restart, 'service[splunk]'
end

This example can be found in the client.rb recipe and the outputs.conf.erb template files that are located in the chef-splunk cookbook that is maintained by Chef.

timezone resource

[edit on GitHub]

Use the timezone resource to change the system timezone.

New in Chef Client 14.6.

Syntax

The timezone resource has the following syntax:

 timezone 'name' do
  timezone      String # default value: 'name' unless specified
  action        Symbol # defaults to :set if not specified
end

where:

  • timezone is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • timezone is the property available to this resource.

Actions

The timezone resource has the following actions:

:set
Set the system timezone.

: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

The timezone resource has the following properties:

timezone

Ruby Type: String | Default Value: 'name'

The timezone value to set.

Examples

Set the timezone to UTC
timezone 'UTC'
Set the timezone to UTC with a friendly resource name
timezone 'Set the hosts timezone to UTC' do
  timezone 'UTC'
end

user resource

[edit on GitHub]

Use the user resource to add users, update existing users, remove users, and to lock/unlock user passwords.

Note

System attributes are collected by Ohai at the start of every chef-client run. By design, the actions available to the user resource are processed after the start of the chef-client run. This means that system attributes added or modified by the user resource during the chef-client run must be reloaded before they can be available to the chef-client. These system attributes can be reloaded in two ways: by picking up the values at the start of the (next) chef-client run or by using the ohai resource to reload the system attributes during the current chef-client run.

Syntax

A user resource block manages users on a node:

user 'a user' do
  comment 'A random user'
  uid '1234'
  gid '1234'
  home '/home/random'
  shell '/bin/bash'
  password '$1$JJsvHslasdfjVEroftprNn4JHtDi'
end

The full syntax for all of the properties that are available to the user resource is:

user 'name' do
  comment                    String
  force                      true, false # see description
  gid                        String, Integer
  home                       String
  iterations                 Integer
  manage_home                true, false
  non_unique                 true, false
  notifies                   # see description
  password                   String
  salt                       String
  shell                      String
  subscribes                 # see description
  system                     true, false
  uid                        String, Integer
  username                   String # defaults to 'name' if not specified
  action                     Symbol # defaults to :create if not specified
end

where

  • user 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
  • comment, force, gid, home, iterations, manage_home, non_unique, password, salt, shell, system, uid, and username 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 user with given properties. If a user already exists (but does not match), update that user to match.
:lock
Lock a user’s password.
:manage
Manage an existing user. This action does nothing if the user does not exist.
:modify
Modify an existing user. This action raises an exception if the user does not exist.
: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 user.
:unlock
Unlock a user’s password.

Properties

This resource has the following properties:

comment

Ruby Type: String

One (or more) comments about the user.

force

Ruby Type: true, false

Force the removal of a user. May be used only with the :remove action.

Warning

Using this property may leave the system in an inconsistent state. For example, a user account will be removed even if the user is logged in. A user’s home directory will be removed, even if that directory is shared by multiple users.

gid

Ruby Type: String, Integer

The identifier for the group. This property was previously named group and both continue to function.

home

Ruby Type: String

The location of the home directory.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

iterations

Ruby Type: Integer

macOS platform only. The number of iterations for a password with a SALTED-SHA512-PBKDF2 shadow hash.

manage_home

Ruby Type: true, false

Manage a user’s home directory.

When used with the :create action, a user’s home directory is created based on HOME_DIR. If the home directory is missing, it is created unless CREATE_HOME in /etc/login.defs is set to no. When created, a skeleton set of files and subdirectories are included within the home directory.

When used with the :modify action, a user’s home directory is moved to HOME_DIR. If the home directory is missing, it is created unless CREATE_HOME in /etc/login.defs is set to no. The contents of the user’s home directory are moved to the new location.

non_unique

Ruby Type: true, false

Create a duplicate (non-unique) user account.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
password

Ruby Type: String

The password shadow hash

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

salt

Ruby Type: String

A SALTED-SHA512-PBKDF2 hash.

shell

Ruby Type: String

The login shell.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
system

Ruby Type: true, false

Create a system user. This property may be used with useradd as the provider to create a system user which passes the -r flag to useradd.

uid

Ruby Type: String, Integer

The numeric user identifier.

username

Ruby Type: String

The name of the user. Default value: the name of the resource block. See “Syntax” section above for more information.

Password Shadow Hash

There are a number of encryption options and tools that can be used to create a password shadow hash. In general, using a strong encryption method like SHA-512 and the passwd command in the OpenSSL toolkit is a good approach, however the encryption options and tools that are available may be different from one distribution to another. The following examples show how the command line can be used to create a password shadow hash. When using the passwd command in the OpenSSL tool:

openssl passwd -1 "theplaintextpassword"

When using mkpasswd:

mkpasswd -m sha-512

For more information:

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 user named “random”

user 'random' do
  manage_home true
  comment 'User Random'
  uid '1234'
  gid '1234'
  home '/home/random'
  shell '/bin/bash'
  password '$1$JJsvHslV$szsCjVEroftprNn4JHtDi'
end

Create a system user

user 'systemguy' do
  comment 'system guy'
  system true
  shell '/bin/false'
end

Create a system user with a variable

The following example shows how to create a system user. In this instance, the home value is calculated and stored in a variable called user_home which sets the user’s home attribute.

user_home = "/home/#{node['cookbook_name']['user']}"

user node['cookbook_name']['user'] do
  gid node['cookbook_name']['group']
  shell '/bin/bash'
  home user_home
  system true
  action :create
end

Use SALTED-SHA512-PBKDF2 passwords

macOS 10.8 (and higher) calculates the password shadow hash using SALTED-SHA512-PBKDF2. The length of the shadow hash value is 128 bytes, the salt value is 32 bytes, and an integer specifies the number of iterations. The following code will calculate password shadow hashes for macOS 10.8 (and higher):

password = 'my_awesome_password'
salt = OpenSSL::Random.random_bytes(32)
iterations = 25000 # Any value above 20k should be fine.

shadow_hash = OpenSSL::PKCS5::pbkdf2_hmac(
  password,
  salt,
  iterations,
  128,
  OpenSSL::Digest::SHA512.new
).unpack('H*').first
salt_value = salt.unpack('H*').first

Use the calculated password shadow hash with the user resource:

user 'my_awesome_user' do
  password 'cbd1a....fc843'  # Length: 256
  salt 'bd1a....fc83'        # Length: 64
  iterations 25000
end

windows_ad_join resource

[edit on GitHub]

Use the windows_ad_join resource to join a Windows Active Directory domain.

New in Chef Client 14.0.

Syntax

The windows_ad_join resource has the following syntax:

windows_ad_join 'name' do
  domain_name          String # default value: 'name' unless specified
  domain_password      String
  domain_user          String
  new_hostname         String
  ou_path              String
  reboot               Symbol # default value: immediate
  sensitive            true, false # default value: true
  action               Symbol # defaults to :join if not specified
end

where:

  • windows_ad_join is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • domain_name, domain_password, domain_user, new_hostname, ou_path, reboot, and sensitive are the properties available to this resource.

Actions

The windows_ad_join resource has the following actions:

:join
Default. Join the Active Directory domain.
: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

The windows_ad_join resource has the following properties:

domain_name

Ruby Type: String | Default Value: 'name'

The FQDN of the Active Directory domain to join.

domain_password

Ruby Type: String | REQUIRED

The password for the domain user. Note that this resource is set to hide sensitive information by default.

domain_user

Ruby Type: String | REQUIRED

The domain user that will be used to join the domain.

new_hostname

Ruby Type: String

“Specifies a new name for the computer in the new domain.”

New in Chef Client 14.5.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
ou_path

Ruby Type: String

The path to the Organizational Unit where the host will be placed.

reboot

Ruby Type: Symbol | Default Value: :immediate

Controls the system reboot behavior after joining the domain, with the following options:

  • :immediate: reboot immediately
  • :delayed: reboot after the Chef Client run completes
  • :never: do not reboot

Note that a reboot is necessary for changes to take effect.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples

Join a domain

windows_ad_join 'ad.example.org' do
  domain_user 'nick'
  domain_password 'p@ssw0rd1'
end

Join a domain, as `win-workstation`

windows_ad_join 'ad.example.org' do
  domain_user 'nick'
  domain_password 'p@ssw0rd1'
  new_hostname 'win-workstation'
end

windows_auto_run resource

[edit on GitHub]

Use the windows_auto_run resource to set applications to run at login.

New in Chef Client 14.0.

Syntax

The windows_auto_run resource has the following syntax:

windows_auto_run 'name' do
  args              String
  path              String
  program_name      String # default value: 'name' unless specified
  root              Symbol # default value: machine
  action            Symbol # defaults to :create if not specified
end

where:

  • windows_auto_run is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • args, path, program_name, and root are the properties available to this resource.

Actions

:create
Create an item to be run at login.
:remove
Remover an item that was previously configured to run at login.
: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

args

Ruby Type: String

Any arguments to be used with the program.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
path

Ruby Type: String

The path to the program that will run at login.

program_name

Ruby Type: String | Default Value: 'name'

The name of the program to run at login, if it differs from the resource block name.

root

Ruby Type: Symbol | Default Value: :machine

The registry root key to put the entry under.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

windows_env resource

[edit on GitHub]

Use the windows_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.

This resource was previously called the env resource; its name was updated in Chef Client 14.0 to reflect the fact that only Windows is supported. Existing cookbooks using env will continue to function, but should be updated to use the new name.

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 windows_env resource.

Syntax

The windows_env resource has the following syntax:

windows_env 'name' do
  delim         String, nil, false
  key_name      String # default value: 'name' unless specified
  user          String # default value: <System>
  value         String
  action        Symbol # defaults to :create if not specified
end

where:

  • windows_env is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • delim, key_name, user, and value are the properties available to 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 Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

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 notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
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

windows_env 'ComSpec' do
  value "C:\\Windows\\system32\\cmd.exe"
end

windows_feature resource

[edit on GitHub]

Use the windows_feature resource to add, remove or entirely delete Windows features and roles. This resource calls the windows_feature_dism or windows_feature_powershell resources depending on the specified installation method, and defaults to DISM, which is available on both Workstation and Server editions of Windows.

New in Chef Client 14.0.

Syntax

The windows_feature resource has the following syntax:

windows_feature 'name' do
  all                   true, false # default value: false
  feature_name          Array, String # default value: 'name' unless specified
  install_method        Symbol
  management_tools      true, false # default value: false
  source                String
  timeout               Integer # default value: 600
  action                Symbol # defaults to :install if not specified
end

where:

  • windows_feature is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • all, feature_name, install_method, management_tools, source, and timeout are the properties available to this resource.

Actions

:install
Default. Install a Windows role / feature using PowerShell.
:remove
Remove a Windows role / feature using PowerShell.
:delete
Delete a Windows role / feature from the image using PowerShell.
: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

all

Ruby Type: true, false | Default Value: false

Install all subfeatures.

feature_name

Ruby Type: Array, String | Default Value: 'name'

The name of the feature(s) or role(s) to install, if it differs from the resource block name.

management_tools

Ruby Type: true, false | Default Value: false

Install all applicable management tools for the roles, role services, or features (PowerShell-only).

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
source

Ruby Type: String

Specify a local repository for the feature install.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: Integer | Default Value: 600

Specifies a timeout (in seconds) for the feature installation.

windows_feature_dism resource

[edit on GitHub]

Use the windows_feature_dism resource to add, remove, or entirely delete Windows features and roles using DISM.

New in Chef Client 14.0.

Syntax

The windows_feature_dism resource has the following syntax:

windows_feature_dism 'name' do
  all               true, false # default value: false
  feature_name      Array, String # default value: 'name' unless specified
  source            String
  timeout           Integer # default value: 600
  action            Symbol # defaults to :install if not specified
end

where:

  • windows_feature_dism is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • all, feature_name, source, and timeout are the properties available to this resource.

Actions

:install
Default. Install a Windows role / feature using DISM.
:remove
Remove a Windows role / feature using DISM.
:delete
Delete a Windows role / feature from the image using DISM.

Properties

all

Ruby Type: true, false | Default Value: false

Install all sub-features. When set to true, this is the equivalent of specifying the /All switch to dism.exe.

feature_name

Ruby Type: Array, String | Default Value: 'name'

The name of the feature(s) or role(s) to install, if it differs from the resource name.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
source

Ruby Type: String

Specify a local repository for the feature install.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: Integer | Default Value: 600

Specifies a timeout (in seconds) for the feature installation.

windows_feature_powershell

[edit on GitHub]

Use the windows_feature_powershell resource to add, remove or entirely delete Windows features and roles using PowerShell. This resource offers significant speed benefits over the windows_feature_dism resource, but requires installation of the Remote Server Administration Tools on non-server releases of Windows.

New in Chef Client 14.0.

Syntax

This resource has the following syntax:

windows_feature_powershell 'name' do
  all                        true, false # default value: 'false'
  feature_name               Array, String # default value: 'name'
  management_tools           true, false # default value: 'false'
  notifies                   # see description
  source                     String
  subscribes                 # see description
  timeout                    Integer # default value: '600'
  action                     Symbol # defaults to :install if not specified
end

where:

  • windows_feature_powershell is the resource
  • 'name' is the name of the feature / role, or the name of the resource block
  • all, feature_name, management_tools, notifies, source, subscribes, and timeout are the properties available to this resource

Actions

:install
Default. Install a Windows role / feature using PowerShell.
:remove
Remove a Windows role / feature using PowerShell.
:delete
Delete a Windows role / feature from the image using PowerShell.
: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

all

Ruby Type: true, false | Default Value: false

Install all subfeatures. When set to true, this is the equivalent of specifying the -InstallAllSubFeatures switch with Add-WindowsFeature.

feature_name

Ruby Type: Array, String | Default Value: 'name'

The name of the feature(s) or role(s) to install, if it differs from the resource block name.

management_tools

Ruby Type: true, false | Default Value: false

Install all applicable management tools for the roles, role services, or features.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
source

Ruby Type: String

Specify a local repository for the feature install.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: Integer | Default Value: 600

Specifies a timeout (in seconds) for the feature installation.

windows_font resource

[edit on GitHub]

Use the windows_font resource to install font files on Windows. By default, the font is sourced from the cookbook using the resource, but a URI source can be specified as well.

New in Chef Client 14.0.

Syntax

The windows_font resource has the following syntax:

windows_font 'name' do
  font_name      String # default value: 'name' unless specified
  source         String
  action         Symbol # defaults to :install if not specified
end

where:

  • windows_font is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • font_name and source are the properties available to this resource.

Actions

:install
Default. Install the font to the system fonts 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

font_name

Ruby Type: String | Default Value: 'name'

The name of the font file to install, if it differs from the resource name.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
source

Ruby Type: String

A local filesystem path or URI that is used to source the font file.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

windows_package resource

[edit on GitHub]

Use the windows_package resource to manage Microsoft Installer Package (MSI) packages for the Microsoft Windows platform.

Syntax

A windows_package resource block manages a package on a node, typically by installing it. The simplest use of the windows_package resource is:

windows_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 windows_package resource is:

windows_package 'name' do
  checksum                     String
  installer_type               Symbol
  options                      String
  package_name                 String, Array
  remote_file_attributes       Hash
  response_file                String
  response_file_variables      Hash
  returns                      String, Integer, Array # default value: [0]
  source                       String
  timeout                      String, Integer # default value: 600
  version                      String, Array
  action                       Symbol # defaults to :install if not specified
end

where:

  • windows_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • checksum, installer_type, options, package_name, remote_file_attributes, response_file, response_file_variables, returns, source, timeout, and version are the properties available to 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:

checksum

Ruby Type: String

The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, the chef-client does not download it. Use when a URL is specified by the source property.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

installer_type

Ruby Type: Symbol

A symbol that specifies the type of package. Possible values: :custom (such as installing a non-.msi file that embeds an .msi-based installer), :inno (Inno Setup), :installshield (InstallShield), :msi (Microsoft Installer Package (MSI)), :nsis (Nullsoft Scriptable Install System (NSIS)), :wise (Wise).

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
options

Ruby Type: String

One (or more) additional options that are passed to the command.

remote_file_attributes

Ruby Type: Hash

A package at a remote location define as a Hash of properties that modifes the properties of the remote_file resource.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns

Ruby Type: Integer, Array of integers | Default Value: 0

A comma-delimited list of return codes that indicate the success or failure of the command that was run remotely. This code signals a successful :install action.

source

Ruby Type: String

Optional. The path to a package in the local file system. The location of the package may be at a URL. Default value: the name of the resource block. See the “Syntax” section above for more information.

If the source property is not specified, the package name MUST be exactly the same as the display name found in Add/Remove programs or exactly the same as the DisplayName property in the appropriate registry key, which may be one of the following:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

Note

If there are multiple versions of a package installed with the same display name, all of those packages will be removed unless a version is provided in the version property or unless it can be discovered in the installer file specified by the source property.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: String, Integer | Default Value: 600 (seconds)

The amount of time (in seconds) to wait before timing out.

version

Ruby Type: String, Array

The version of a package to be installed or upgraded.

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

windows_package '7zip' do
  action :install
  source 'C:\7z920.msi'
end

Specify a URL for the source attribute

windows_package '7zip' do
  source 'http://www.7-zip.org/a/7z938-x64.msi'
end

Specify path and checksum

windows_package '7zip' do
  source 'http://www.7-zip.org/a/7z938-x64.msi'
  checksum '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3'
end

Modify remote_file resource attributes

The windows_package resource may specify a package at a remote location using the remote_file_attributes property. This uses the remote_file resource to download the contents at the specified URL and passes in a Hash that modifes the properties of the remote_file resource.

For example:

windows_package '7zip' do
  source 'http://www.7-zip.org/a/7z938-x64.msi'
  remote_file_attributes ({
    :path => 'C:\\7zip.msi',
    :checksum => '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3'
  })
end

Download a nsis (Nullsoft) package resource

windows_package 'Mercurial 3.6.1 (64-bit)' do
  source 'http://mercurial.selenic.com/release/windows/Mercurial-3.6.1-x64.exe'
  checksum 'febd29578cb6736163d232708b834a2ddd119aa40abc536b2c313fc5e1b5831d'
end

Download a custom package

windows_package 'Microsoft Visual C++ 2005 Redistributable' do
  source 'https://download.microsoft.com/download/6/B/B/6BB661D6-A8AE-4819-B79F-236472F6070C/vcredist_x86.exe'
  installer_type :custom
  options '/Q'
end

windows_pagefile resource

[edit on GitHub]

Use the windows_pagefile resource to configure pagefile settings on Windows.

New in Chef Client 14.0.

Syntax

The windows_pagefile resource has the following syntax:

windows_pagefile 'name' do
  automatic_managed      true, false # default value: false
  initial_size           Integer
  maximum_size           Integer
  path                   String # default value: 'name' unless specified
  system_managed         true, false
  action                 Symbol # defaults to :set if not specified
end

where:

  • windows_pagefile is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • automatic_managed, initial_size, maximum_size, path, and system_managed are the properties available to this resource.

Actions

The windows_pagefile resource has the following actions:

:set
Default. Configures the default pagefile, creating if it doesn’t exist.
:delete
Deletes the specified pagefile.
: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

The windows_pagefile resource has the following properties:

automatic_managed

Ruby Type: true, false | Default Value: false

Enable automatic management of pagefile initial and maximum size. Setting this to true ignores ‘initial_size’ and ‘maximum_size’ properties.

initial_size

Ruby Type: Integer

Initial size of the pagefile in megabytes.

maximum_size

Ruby Type: Integer

Maximum size of the pagefile in megabytes.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
path

Ruby Type: String | Default Value: 'name'

The path to the pagefile if different from the resource name.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

system_managed

Ruby Type: true, false

Configures whether the system manages the pagefile size.

windows_path resource

[edit on GitHub]

Use the windows_path resource to manage the path environment variable on Microsoft Windows.

New in Chef Client 13.4.

Syntax

The windows_path resource has the following syntax:

windows_path 'name' do
  path      String # default value: 'name' unless specified
  action    Symbol # defaults to :add if not specified
end

where:

  • windows_path is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • path is the property available to this resource.

Actions

The windows_path resource has the following actions:

:add
Add an item to the system path
:remove
Remove an item from the system path

Properties

The windows_path resource has the following properties:

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
path
Ruby Type: String Name property. The name of the value to add to the system path
subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples

Add Sysinternals to the system path

windows_path 'C:\Sysinternals' do
  action :add
end

Remove 7-Zip from the system path

windows_path 'C:\7-Zip' do
  action :remove
end

windows_printer resource

[edit on GitHub]

Use the windows_printer resource to setup Windows printers. Note that this doesn’t currently install a printer driver. You must already have the driver installed on the system.

New in Chef Client 14.0.

Syntax

The windows_printer resource has the following syntax:

windows_printer 'name' do
  comment           String
  default           true, false # default value: false
  device_id         String # default value: 'name' unless specified
  driver_name       String
  exists            true, false
  ipv4_address      String
  location          String
  share_name        String
  shared            true, false # default value: false
  action            Symbol # defaults to :create if not specified
end

where:

  • windows_printer is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • comment, default, device_id, driver_name, exists, ipv4_address, location, share_name, and shared are the properties available to this resource.

Actions

The windows_printer resource has the following actions:

:create
Default. Create a new printer and printer port, if one doesn’t already exist.
:delete
Delete an existing printer. Note that this resource does not delete the associated printer port.
: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

The windows_printer resource has the following properties:

comment

Ruby Type: String

Optional descriptor for the printer queue.

default

Ruby Type: true, false | Default Value: false

Determines whether or not this should be the system’s default printer.

device_id

Ruby Type: String | Default Value: 'name'

Printer queue name, such as: "HP LJ 5200 in fifth floor copy room".

driver_name

Ruby Type: String | REQUIRED

The exact name of the installed printer driver on the system.

ipv4_address

Ruby Type: String

The IPv4 address of the printer, such as ‘10.4.64.23’.

location

Ruby Type: String

Printer location, such as: "2nd floor copy room".

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
share_name

Ruby Type: String

The name used to identify the shared printer.

shared

Ruby Type: true, false | Default Value: false

Determines whether or not the printer is shared.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

windows_printer_port resource

[edit on GitHub]

Use the windows_printer_port resource to create and delete TCP/IPv4 printer ports on Windows.

New in Chef Client 14.0.

Syntax

The windows_printer_port resource has the following syntax:

windows_printer_port 'name' do
  exists                true, false
  ipv4_address          String # default value: 'name' unless specified
  port_description      String
  port_name             String
  port_number           Integer # default value: 9100
  port_protocol         Integer # default value: 1
  snmp_enabled          true, false # default value: false
  action                Symbol # defaults to :create if not specified
end

where:

  • windows_printer_port is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • exists, ipv4_address, port_description, port_name, port_number, port_protocol, and snmp_enabled are the properties available to this resource.

Actions

The windows_printer_port resource has the following actions:

:create
Default. Create the printer port, if one doesn’t already exist.
:delete
Delete an existing printer port.
: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

The windows_printer_port resource has the following properties:

ipv4_address

Ruby Type: String | Default Value: 'name'

The IPv4 address of the printer, if it differs from the resource block name.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
port_description

Ruby Type: String

The description of the port.

port_name

Ruby Type: String

The port name.

port_number

Ruby Type: Integer | Default Value: 9100

The port number.

port_protocol

Ruby Type: Integer | Default Value: 1

The printer port protocol; 1 (RAW) or 2 (LPR).

snmp_enabled

Ruby Type: true, false | Default Value: false

Determines if SNMP is enabled on the port

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

windows_service resource

[edit on GitHub]

Use the windows_service resource to create, delete, or manage a service on the Microsoft Windows platform.

Syntax

A windows_service resource block manages the state of a service on a machine that is running Microsoft Windows. For example:

windows_service 'BITS' do
  action :configure_startup
  startup_type :manual
end

The full syntax for all of the properties that are available to the windows_service resource is:

windows_service 'name' do
  binary_path_name           String
  desired_access             Integer
  delayed_start              [Integer] # This only applies if startup_type is :automatic
  dependencies               [String, Array]
  description                String
  desired_access             Integer # defaults to 983551
  display_name               String
  error_control              Integer
  init_command               String
  load_order_group           String
  notifies                   # see description
  pattern                    String
  reload_command             String # not used on the Windows platform
  restart_command            String
  run_as_password            String
  run_as_user                String
  service_name               String # defaults to 'name' if not specified
  service_type               Integer # defaults to 'SERVICE_WIN32_OWN_PROCESS'
  start_command              String
  startup_type               Symbol
  status_command             String
  stop_command               String
  subscribes                 # see description
  supports                   Hash
  timeout                    Integer
  action                     Symbol # defaults to :nothing if not specified
end

where:

  • windows_service 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
  • binary_path_name, display_name, desired_access, delayed_start, dependencies, description, error_control, init_command, load_order_group, pattern, reload_command, restart_command, run_as_password, run_as_user, service_name, service_type, start_command, startup_type, status_command, stop_command, supports, and timeout are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions

The windows_service resource has the following actions:

:configure_startup
Configure a service based on the value of the startup_type property.
:create

Create the service based on the value of the binary_path_name, service_name and/or display_name property.

New in Chef Client 14.0.

:delete

Delete the service based on the value of the service_name property.

New in Chef Client 14.0.

:disable
Disable a service. This action is equivalent to a Disabled startup type on the Microsoft Windows platform.
:enable
Enable a service at boot. This action is equivalent to an Automatic startup type on the Microsoft Windows platform.
:nothing
Default. Do nothing with a service.
:reload
Reload the configuration for this service. This action is not supported on the Windows platform and will raise an error if used.
:restart
Restart a service.
:start
Start a service, and keep it running until stopped or disabled.
:stop
Stop a service.

Properties

The windows_service resource has the following properties:

binary_path_name

Ruby Type: String

Required The fully qualified path to the service binary file. The path can also include arguments for an auto-start service.

New in Chef Client 14.0.

display_name

Ruby Type: String

The display name to be used by user interface programs to identify the service. This string has a maximum length of 256 characters.

New in Chef Client 14.0.

delayed_start

Ruby Type: Integer

Set the startup type to delayed start. This only applies if startup_type is :automatic.

New in Chef Client 14.0.

dependencies

Ruby Type: String, Array

A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify nil or an empty string if the service has no dependencies. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group.

New in Chef Client 14.0.

description

Ruby Type: String

Description of the service.

New in Chef Client 14.0.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

init_command

Ruby Type: String

The path to the init script that is associated with the service. This is typically /etc/init.d/SERVICE_NAME. The init_command property can be used to prevent the need to specify overrides for the start_command, stop_command, and restart_command attributes.

load_order_group

Ruby Type: String

The name of the service’s load ordering group(s). Specify nil or an empty string if the service does not belong to a group.

New in Chef Client 14.0.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
pattern

Ruby Type: String | Default Value: service_name

The pattern to look for in the process table.

reload_command

Ruby Type: String

The command used to tell a service to reload its configuration.

restart_command

Ruby Type: String

The command used to restart a service.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

run_as_password

Ruby Type: String

The password for the user specified by run_as_user.

run_as_user

Ruby Type: String

The user under which a Microsoft Windows service runs.

service_name

Ruby Type: String

The name of the service. Default value: the name of the resource block. See the “Syntax” section above for more information.

start_command

Ruby Type: String

The command used to start a service.

startup_type

Ruby Type: Symbol | Default Value: :automatic

Use to specify the startup type for a Microsoft Windows service. Possible values: :automatic, :disabled, or :manual.

status_command

Ruby Type: String

The command used to check the run status for a service.

stop_command

Ruby Type: String

The command used to stop a service.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
supports

Ruby Type: Hash

A list of properties that controls how the chef-client is to attempt to manage a service: :restart, :reload, :status. For :restart, the init script or other service provider can use a restart command; if :restart is not specified, the chef-client attempts to stop and then start a service. For :reload, the init script or other service provider can use a reload command. For :status, the init script or other service provider can use a status command to determine if the service is running; if :status is not specified, the chef-client attempts to match the service_name against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: { restart: false, reload: false, status: false } for all platforms (except for the Red Hat platform family, which defaults to { restart: false, reload: false, status: true }.)

timeout

Ruby Type: Integer | Default Value: 60

The amount of time (in seconds) to wait before timing out.

Examples

The following examples demonstrate various approaches for using resources in recipes. If you want to see examples of how Chef uses resources in recipes, take a closer look at the cookbooks that Chef authors and maintains: https://github.com/chef-cookbooks.

Start a service manually

windows_service 'BITS' do
  action :configure_startup
  startup_type :manual
end

Create a service

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
end

Create service with ‘service_name’ and ‘display_name’:

windows_service 'Create chef client as service' do
  action :create
  display_name "CHEF-CLIENT"
  service_name "chef-client"
  binary_path_name "C:\\opscode\\chef\\bin"
end

Create service with the :manual startup type:

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :manual
end

Create a service with the :disabled startup type:

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :disabled
end

Create service with the :automatic startup type and delayed start enabled:

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :automatic
  delayed_start true
end

Create service with a description:

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :automatic
  description "Chef client as service"
end

Delete a service

Delete service with the 'name' of chef-client:

windows_service 'chef-client' do
  action :delete
end

Delete service with 'service_name':

windows_service 'Delete chef client' do
  action :delete
  service_name "chef-client"
end

Configure a service

Change an existing service from automatic to manual startup:

windows_service 'chef-client' do
  action :configure
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :manual
end

windows_shortcut resource

[edit on GitHub]

Use the windows_shortcut resource to create shortcut files on Windows.

New in Chef Client 14.0.

Syntax

The windows_shortcut resource has the following syntax:

windows_shortcut 'name' do
  arguments          String
  cwd                String
  description        String
  iconlocation       String
  shortcut_name      String # default value: 'name' unless specified
  target             String
  action             Symbol # defaults to :create if not specified
end

where:

  • windows_shortcut is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • arguments, cwd, description, iconlocation, shortcut_name, and target are the properties available to this resource.

Actions

The windows_shortcut resource has the following actions:

:create
Default. Create or modify a Windows shortcut.
: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

The windows_shortcut resource has the following properties:

arguments

Ruby Type: String

Arguments to pass to the target when the shortcut is executed.

cwd

Ruby Type: String

Working directory to use when the target is executed.

description

Ruby Type: String

The description of the shortcut

iconlocation

Ruby Type: String

Icon to use for the shortcut. Accepts the format of 'path, index', where index is the icon file to use. See Microsoft’s documentation for details.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
shortcut_name

Ruby Type: String | Default Value: 'name'

The name for the shortcut, if it differs from the resource name.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
target

Ruby Type: String

The destination that the shortcut links to.

windows_task resource

[edit on GitHub]

Use the windows_task resource to create, delete or run a Windows scheduled task. Requires Windows Server 2008 or later due to API usage.

New in Chef Client 13.0.

Note

The windows_task resource that was provided as part of the windows cookbook included the :change action, which has been removed from windows_task in Chef client. The :create action can be used instead to update an existing task.

Syntax

The windows_task resource has the following syntax:

windows_task 'name' do
  command                             String
  cwd                                 String
  day                                 String, Integer
  disallow_start_if_on_batteries      true, false # default value: false
  execution_time_limit                String, Integer # default value: PT72H
  force                               true, false # default value: false
  frequency                           Symbol
  frequency_modifier                  Integer, String # default value: 1
  idle_time                           Integer
  interactive_enabled                 true, false # default value: false
  minutes_duration                    String, Integer
  minutes_interval                    String, Integer
  months                              String
  password                            String
  priority                            Integer # default value: 7
  random_delay                        String, Integer
  run_level                           Symbol # default value: limited
  start_day                           String
  start_time                          String
  stop_if_going_on_batteries          true, false # default value: false
  task_name                           String # default value: 'name' unless specified
  user                                String # default value: SYSTEM
  action                              Symbol # defaults to :create if not specified
end

where:

  • windows_task is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • command, cwd, day, disallow_start_if_on_batteries, execution_time_limit, force, frequency, frequency_modifier, idle_time, interactive_enabled, minutes_duration, minutes_interval, months, password, priority, random_delay, run_level, start_day, start_time, stop_if_going_on_batteries, task_name, and user are the properties available to this resource.

Actions

The windows_task resource has the following actions:

:create
Creates a task, or updates an existing task if any property has changed.
:delete
Deletes a task.
:run
Runs a task.
:end
Ends a task.
:enable
Enables a task.
:disable
Disables a task.

Properties

The windows_task resource has the following properties:

command

Ruby Type: String

The command to be executed by the windows scheduled task.

cwd

Ruby Type: String

The directory the task will be run from.

day

Ruby Type: String, Integer

The day(s) on which the task runs.
  • Use with frequency :monthly and :weekly tasks,
  • Valid values with frequency :weekly are MON-SUN or \*.
  • Valid values with frequency :monthly are 1-31 `` or ``MON to SUN and LASTDAY.
    • Use MON-SUN or LASTDAY if you are setting frequency_modiifer as "FIRST, SECOND, THIRD etc." else use 1-31.
    • Multiple days should be comma seprated. e.g "1, 2, 3" or "MON, WEN, FRI".
disallow_start_if_on_batteries

Ruby Type: true, false | Default Value: false

Disallow start of the task if the system is running on battery power. New in Chef Client 14.4.

execution_time_limit

Ruby Type: String, Integer | Default Value: PT72H (72 hours)

The maximum time (in seconds) the task will run.

force

Ruby Type: true, false | Default Value: false

When used with create, will update the task.

frequency

Ruby Type: Symbol

  • Frequency with which to run the task.
  • This is a mandatory property in Chef 14.1
  • Valid values: :minute, :hourly, :daily, :weekly, :monthly, :none, :once, :on_logon, :onstart, :on_idle.
  • The :once value requires the start_time property.
  • The :none frequency requires Chef 13.6 or later.
frequency_modifier

Ruby Type: Integer, String | Default Value: 1

  • For frequency :minute valid values are 1 to 1439
  • For frequency :hourly valid values are 1 to 23
  • For frequency :daily valid values are 1 to 365
  • For frequency :weekly valid values are 1 to 52
  • For frequency :monthly valid values are ('FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST') OR 1-12.
    • e.g. If user want to run the task on second week of the month use frequency_modifier value as SECOND. Multiple values for weeks of the month should be comma seperated e.g. "FIRST, THIRD, LAST".
    • To run task every (n) months user values ‘1-12’.
idle_time

Ruby Type: Integer

For :on_idle frequency, the time (in minutes) without user activity that must pass to trigger the task, from 1 - 999.

interactive_enabled

Ruby Type: true, false | Default Value: false

Allow task to run interactively or non-interactively. Requires user and password to also be set.

minutes_duration
Ruby Type: String, Integer
minutes_interval
Ruby Type: String, Integer
months

Ruby Type: String

The Months of the year on which the task runs, such as: "JAN, FEB" or "\*". Multiple months should be comma delimited. e.g. "Jan, Feb, Mar, Dec"

password

Ruby Type: String

The user’s password. The user property must be set if using this property.

priority

Ruby Type: Integer | Default Value: 7

Use to set Priority Levels range from 0 to 10.

random_delay

Ruby Type: String, Integer

Delays the task up to a given time (in seconds).

run_level

Ruby Type: Symbol | Default Value: :limited

Run with :limited or :highest privileges.

start_day

Ruby Type: String

Specifies the first date on which the task runs in MM/DD/YYYY format.

start_time

Ruby Type: String

Specifies the start time to run the task, in HH:mm format.

stop_if_going_on_batteries

Ruby Type: true, false | Default Value: false

Scheduled task option when system is switching on battery. New in Chef Client 14.4.

task_name

Ruby Type: String | Default Value: 'name'

The task name, such as "Task Name" or "/Task Name"

user

Ruby Type: String | Default Value: SYSTEM

The user to run the task as.

Examples

Create a scheduled task to run every 15 minutes as the Administrator user

windows_task 'chef-client' do
  user 'Administrator'
  password 'password'
  command 'chef-client'
  run_level :highest
  frequency :minute
  frequency_modifier 15
end

Create a scheduled task to run every 2 days

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :daily
  frequency_modifier 2
end

Create a scheduled task to run on specific days of the week

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :weekly
  day 'Mon, Thu'
end

Create a scheduled task to run only once

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :once
  start_time "16:10"
end

Create a scheduled task to run on current day every 3 weeks and delay upto 1 min

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :weekly
  frequency_modifier 3
  random_delay '60'
end

Create a scheduled task to run weekly starting on Dec 28th 2018

windows_task 'chef-client 8' do
  command 'chef-client'
  run_level :highest
  frequency :weekly
  start_day '12/28/2018'
end

Create a scheduled task to run every Monday, Friday every 2 weeks

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :weekly
  frequency_modifier 2
  day 'Mon, Fri'
end

Create a scheduled task to run when computer is idle with idle duration 20 min

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :on_idle
  idle_time 20
end

Delete a task named “old task”

windows_task 'old task' do
  action :delete
end

Enable a task named “chef-client”

windows_task 'chef-client' do
  action :enable
end

Disable a task named “ProgramDataUpdater” with TaskPath “\Microsoft\Windows\Application Experience\ProgramDataUpdater”

windows_task '\Microsoft\Windows\Application Experience\ProgramDataUpdater' do
  action :disable
end

windows_workgroup resource

[edit on GitHub]

Use the windows_workgroup resource to join or change the workgroup of a Windows host.

New in Chef Client 14.5.

Syntax

The windows_workgroup resource has the following syntax:

windows_workgroup 'name' do
  password            String
  reboot              Symbol # default value: immediate
  sensitive           true, false # default value: true
  user                String
  workgroup_name      String # default value: 'name' unless specified
  action              Symbol # defaults to :join if not specified
end

where:

  • windows_workgroup is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • password, reboot, sensitive, user, and workgroup_name are the properties available to this resource.

Actions

The windows_workgroup resource has the following actions:

:join
Update the workgroup.
: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

The windows_workgroup resource has the following properties:

password

Ruby Type: String

The password for the local administrator user.

reboot

Ruby Type: Symbol | Default Value: immediate

Controls the system reboot behavior post workgroup joining. Reboot immediately, after the Chef run completes, or never. Note that a reboot is necessary for changes to take effect.

sensitive
Ruby Type: true, false | Default Value: true
user

Ruby Type: String

The local administrator user to use to change the workgroup.

workgroup_name

Ruby Type: String | Default Value: 'name'

The name of the workgroup for the computer.

Common Resource Functionality

Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by the chef-client.

Notifications

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

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.

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.

yum_package resource

[edit on GitHub]

Use the yum_package resource to install, upgrade, and remove packages with Yum for the Red Hat and CentOS platforms. The yum_package resource is able to resolve provides data for packages much like Yum can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides, and library names.

Note

Support for using file names to install packages (as in yum_package "/bin/sh") is not available because the volume of data required to parse for this is excessive.

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 yum_package resource block manages a package on a node, typically by installing it. The simplest use of the yum_package resource is:

yum_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The yum_package resource has the following syntax:

yum_package 'name' do
  allow_downgrade            true, false # default value: false
  arch                       String, Array
  flush_cache                Hash # default value: {"before"=>false, "after"=>false}
  options                    String, Array
  package_name               String, Array # defaults to 'name' if not specified
  source                     String
  timeout                    String, Integer
  version                    String, Array
  yum_binary                 String
  action                     Symbol # defaults to :install if not specified
end

where:

  • yum_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • allow_downgrade, arch, flush_cache, options, package_name, response_file, response_file_variables, source, timeout, version, and yum_binary are the properties available to this resource.

Actions

The yum_package 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 yum package to a specific version.
: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.
:unlock
Unlocks the yum package so that it can be upgraded to a newer version.
:upgrade
Install a package and/or ensure that a package is the latest version. This action will ignore the version attribute.

Properties

This resource has the following properties:

allow_downgrade

Ruby Type: true, false | Default Value: false

Downgrade a package to satisfy requested version requirements.

arch

Ruby Type: String, Array

The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name.

flush_cache

Ruby Type: Array, Hash | Default Value: {"before"=>false, "after"=>false}

Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Default value: [ :before, :after ]. The value may also be a Hash: ( { :before => true/false, :after => true/false } ).

Yum automatically synchronizes remote metadata to a local cache. The chef-client creates a copy of the local cache, and then stores it in-memory during the chef-client run. The in-memory cache allows packages to be installed during the chef-client run without the need to continue synchronizing the remote metadata to the local cache while the chef-client run is in-progress.

As an array:

yum_package 'some-package' do
  #...
  flush_cache [ :before ]
  #...
end

and as a Hash:

yum_package 'some-package' do
  #...
  flush_cache( { :after => true } )
  #...
end

Note

The flush_cache property does not flush the local Yum cache! Use Yum tools—yum clean headers, yum clean packages, yum clean all—to clean the local Yum cache.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
options

Ruby Type: String, Array

One (or more) additional command options that are passed to the command.

package_name

Ruby Type: String, Array

One of the following: the name of a package, the name of a package and its architecture, the name of a dependency. Default value: the name of the resource block. See “Syntax” section above for more information.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

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.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Type: String, Array

The version of a package to be installed or upgraded. This property is ignored when using the :upgrade action.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Yum, DNF, 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 %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(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.

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 an exact version

yum_package 'netpbm = 10.35.58-8.el5'

Install a minimum version

yum_package 'netpbm >= 10.35.58-8.el5'

Install a minimum version using the default action

yum_package 'netpbm'

To install a package

yum_package 'netpbm' do
  action :install
end

To install a partial minimum version

yum_package 'netpbm >= 10'

To install a specific architecture

yum_package 'netpbm' do
  arch 'i386'
end

or:

yum_package 'netpbm.x86_64'

To install a specific version-release

yum_package 'netpbm' do
  version '10.35.58-8.el5'
end

To install a specific version (even when older than the current)

yum_package 'tzdata' do
  version '2011b-1.el5'
  allow_downgrade true
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

yum_repository resource

[edit on GitHub]

Use the yum_repository resource to manage a Yum repository configuration file located at /etc/yum.repos.d/repositoryid.repo on the local machine. This configuration file specifies which repositories to reference, how to handle cached data, etc.

New in Chef Client 12.14.

Syntax

The yum_repository resource has the following syntax:

yum_repository 'name' do
  baseurl                    String, Array
  clean_headers              true, false # default value: false
  clean_metadata             true, false # default value: true
  cost                       String
  description                String # default value: Yum Repository
  enabled                    true, false # default value: true
  enablegroups               true, false
  exclude                    String
  failovermethod             String
  fastestmirror_enabled      true, false
  gpgcheck                   true, false # default value: true
  gpgkey                     String, Array
  http_caching               String
  include_config             String
  includepkgs                String
  keepalive                  true, false
  make_cache                 true, false # default value: true
  max_retries                String, Integer
  metadata_expire            String
  metalink                   String
  mirror_expire              String
  mirrorlist                 String
  mirrorlist_expire          String
  mode                       String, Integer # default value: 0644
  options                    Hash
  password                   String
  priority                   String
  proxy                      String
  proxy_password             String
  proxy_username             String
  repo_gpgcheck              true, false
  report_instanceid          true, false
  repositoryid               String # default value: 'name' unless specified
  skip_if_unavailable        true, false
  source                     String
  sslcacert                  String
  sslclientcert              String
  sslclientkey               String
  sslverify                  true, false
  throttle                   String, Integer
  timeout                    String
  username                   String
  action                     Symbol # defaults to :create if not specified
end

where:

  • yum_repository is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • baseurl, clean_headers, clean_metadata, cost, description, enabled, enablegroups, exclude, failovermethod, fastestmirror_enabled, gpgcheck, gpgkey, http_caching, include_config, includepkgs, keepalive, make_cache, max_retries, metadata_expire, metalink, mirror_expire, mirrorlist, mirrorlist_expire, mode, options, password, priority, proxy, proxy_password, proxy_username, repo_gpgcheck, report_instanceid, repositoryid, skip_if_unavailable, source, sslcacert, sslclientcert, sslclientkey, sslverify, throttle, timeout, and username are the properties available to this resource.

Actions

The yum_repository resource has the following actions:

:create
Creates a repository file and builds the repository listing.
:delete
Deletes the repository file.
:makecache
Updates the yum cache.

Properties

This resource has the following properties:

baseurl

Ruby Type: String, Array

URL to the directory where the Yum repository’s ‘repodata’ directory lives. Can be an http://, https:// or a ftp:// URL. You can specify multiple URLs in one baseurl statement.

clean_headers

Ruby Type: true, false | Default Value: false | DEPRECATED

Specifies whether you want to purge the package data files that are downloaded from a Yum repository and held in a cache directory.

clean_metadata

Ruby Type: true, false | Default Value: true

Specifies whether you want to purge all of the packages downloaded from a Yum repository and held in a cache directory.

cost

Ruby Type: String

Relative cost of accessing this repository. Useful for weighing one repo’s packages as greater/less than any other.

description

Ruby Type: String | Default Value: Yum Repository

Descriptive name for the repository channel and maps to the ‘name’ parameter in a repository .conf.

enabled

Ruby Type: true, false | Default Value: true

Specifies whether or not Yum should use this repository.

enablegroups

Ruby Type: true, false

Specifies whether Yum will allow the use of package groups for this repository.

exclude

Ruby Type: String

List of packages to exclude from updates or installs. This should be a space separated list. Shell globs using wildcards (eg. * and ?) are allowed.

failovermethod

Ruby Type: String

Method to determine how to switch to a new server if the current one fails, which can either be roundrobin or priority. roundrobin randomly selects a URL out of the list of URLs to start with and proceeds through each of them as it encounters a failure contacting the host. priority starts from the first baseurl listed and reads through them sequentially.

fastestmirror_enabled

Ruby Type: true, false

Specifies whether to use the fastest mirror from a repository configuration when more than one mirror is listed in that configuration.

gpgcheck

Ruby Type: true, false | Default Value: true

Specifies whether or not Yum should perform a GPG signature check on the packages received from a repository.

gpgkey

Ruby Type: String, Array

URL pointing to the ASCII-armored GPG key file for the repository. This is used if Yum needs a public key to verify a package and the required key hasn’t been imported into the RPM database. If this option is set, Yum will automatically import the key from the specified URL.

Multiple URLs may be specified in the same manner as the baseurl option. If a GPG key is required to install a package from a repository, all keys specified for that repository will be installed.

http_caching

Ruby Type: String

Determines how upstream HTTP caches are instructed to handle any HTTP downloads that Yum does. This option can take the following values:

  • all means that all HTTP downloads should be cached.
  • packages means that only RPM package downloads should be cached, but not repository metadata downloads.
  • none means that no HTTP downloads should be cached.

The default is all. This is recommended unless you are experiencing caching related issues.

include_config

Ruby Type: String

An external configuration file using the format url://to/some/location.

includepkgs

Ruby Type: String

Inverse of exclude property. This is a list of packages you want to use from a repository. If this option lists only one package then that is all Yum will ever see from the repository.

keepalive

Ruby Type: true, false

Determines whether or not HTTP/1.1 keep-alive should be used with this repository.

make_cache

Ruby Type: true, false | Default Value: true

Determines whether package files downloaded by Yum stay in cache directories. By using cached data, you can carry out certain operations without a network connection.

max_retries

Ruby Type: String, Integer

Number of times any attempt to retrieve a file should retry before returning an error. Setting this to ‘0’ makes Yum try forever.

metadata_expire

Ruby Type: String

Time (in seconds) after which the metadata will expire. If the current metadata downloaded is less than the value specified, then Yum will not update the metadata against the repository. If you find that Yum is not downloading information on updates as often as you would like lower the value of this option. You can also change from the default of using seconds to using days, hours or minutes by appending a ‘d’, ‘h’ or ‘m’ respectively. The default is six hours to compliment yum-updates running once per hour. It is also possible to use the word never, meaning that the metadata will never expire. Note: When using a metalink file, the metalink must always be newer than the metadata for the repository due to the validation, so this timeout also applies to the metalink file.

Note

When using a metalink file, the metalink must always be newer than the metadata for the repository due to the validation, so this timeout also applies to the metalink file.

metalink

Ruby Type: String

Specifies a URL to a metalink file for the repomd.xml, a list of mirrors for the entire repository are generated by converting the mirrors for the repomd.xml file to a baseurl.

mirror_expire

Ruby Type: String

Time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than this many seconds old then Yum will not download another copy of the mirrorlist, it has the same extra format as metadata_expire. If you find that Yum is not downloading the mirrorlists as often as you would like lower the value of this option.

mirrorlist

Ruby Type: String

URL to a file containing a list of baseurls. This can be used instead of or with the baseurl option. Substitution variables, described below, can be used with this option.

mirrorlist_expire

Ruby Type: String

Specifies the time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than the value specified, then Yum will not download another copy of the mirrorlist.

mode

Ruby Type: String, Integer | Default Value: 0644

Permissions mode of .repo file on disk. This is useful for scenarios where secrets are in the repo file. If this value is set to ‘600’, normal users will not be able to use Yum search, Yum info, etc.

options

Ruby Type: Hash

Specifies the repository options.

password

Ruby Type: String

Password to use with the username for basic authentication.

priority

Ruby Type: String

Assigns a priority to a repository where the priority value is between ‘1’ and ‘99’ inclusive. Priorities are used to enforce ordered protection of repositories. Packages from repositories with a lower priority (higher numerical value) will never be used to upgrade packages that were installed from a repository with a higher priority (lower numerical value). The repositories with the lowest numerical priority number have the highest priority.

proxy

Ruby Type: String

URL to the proxy server that Yum should use.

proxy_password

Ruby Type: String

Password for this proxy.

proxy_username

Ruby Type: String

Username to use for proxy.

repo_gpgcheck

Ruby Type: true, false

Determines whether or not Yum should perform a GPG signature check on the repodata from this repository.

report_instanceid

Ruby Type: true, false

Determines whether to report the instance ID when using Amazon Linux AMIs and repositories.

repositoryid

Ruby Type: String | Default Value: 'name'

Specifies a unique name for each repository, one word. Defaults to name attribute.

skip_if_unavailable

Ruby Type: true, false

Allow yum to continue if this repository cannot be contacted for any reason.

source

Ruby Type: String

Use a custom template source instead of the default one.

sslcacert

Ruby Type: String

Path to the directory containing the databases of the certificate authorities Yum should use to verify SSL certificates.

sslclientcert

Ruby Type: String

Path to the SSL client certificate Yum should use to connect to repos/remote sites.

sslclientkey

Ruby Type: String

Path to the SSL client key Yum should use to connect to repos/remote sites.

sslverify

Ruby Type: true, false

Determines whether Yum will verify SSL certificates/hosts.

throttle

Ruby Type: String, Integer

Enable bandwidth throttling for downloads.

timeout

Ruby Type: String

Number of seconds to wait for a connection before timing out. Defaults to 30 seconds. This may be too short of a time for extremely overloaded sites.

username

Ruby Type: String

Username to use for basic authentication to a repository.

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.

Add internal company repository

yum_repository 'OurCo' do
  description 'OurCo yum repository'
  mirrorlist 'http://artifacts.ourco.org/mirrorlist?repo=ourco-6&arch=$basearch'
  gpgkey 'http://artifacts.ourco.org/pub/yum/RPM-GPG-KEY-OURCO-6'
  action :create
end

Delete a repository

yum_repository 'CentOS-Media' do
  action :delete
end

zypper_package resource

[edit on GitHub]

Use the zypper_package resource to install, upgrade, and remove packages with Zypper for the SUSE Enterprise and OpenSUSE 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 zypper_package resource block manages a package on a node, typically by installing it. The simplest use of the zypper_package resource is:

zypper_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The zypper_package resource has the following syntax:

zypper_package 'name' do
  allow_downgrade              true, false # default value: false
  gpg_check                    true, false
  options                      String, Array
  package_name                 String, Array
  source                       String
  timeout                      String, Integer
  version                      String, Array
  action                       Symbol # defaults to :install if not specified
end

where:

  • zypper_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • allow_downgrade, gpg_check, options, package_name, source, and timeout are the properties available to this resource.

Actions

The zypper_package 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 zypper package to a specific version.
: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 zypper package so that it can be upgraded to a newer version.
:upgrade
Install a package and/or ensure that a package is the latest version.
: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

The zypper_package resource has the following properties:

allow_downgrade

Ruby Type: true, false | Default Value: false

Allow downgrading a package to satisfy requested version requirements.

New in Chef Client 13.6.

gpg_check

Ruby Type: true, false | Default Value: true

Verify the package’s GPG signature. Can also be controlled site-wide using the zypper_check_gpg config option.

ignore_failure

Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
options

Ruby Type: String, Array

One (or more) additional command options that are passed to the command. For example, common zypper directives, such as --no-recommends. See the zypper man page for the full list.

package_name

Ruby Type: String, Array

The name of the package. Defaults to the name of the resourse block unless specified.

retries

Ruby Type: Integer | Default Value: 0

The number of times to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source

Ruby Type: String

The direct path to a the package on the host.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
timeout

Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version

Ruby Type: 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, DNF, 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 %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(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.

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

zypper_package 'name of package' do
  action :install
end

Install a package using local file

zypper_package 'jwhois' do
  action :install
  source '/path/to/jwhois.rpm'
end

Install without using recommend packages as a dependency

package 'apache2' do
  options '--no-recommends'
end

zypper_repository resource

[edit on GitHub]

Use the zypper_repository resource to create Zypper package repositories on SUSE Enterprise Linux and openSUSE systems. This resource maintains full compatibility with the zypper_repository resource in the existing zypper cookbook.

New in Chef Client 13.3.

Syntax

The zypper_repository resource has the following syntax:

zypper_repository 'name' do
  autorefresh            true, false # default value: true
  baseurl                String
  cookbook               String
  description            String
  enabled                true, false # default value: true
  gpgautoimportkeys      true, false # default value: true
  gpgcheck               true, false # default value: true
  gpgkey                 String
  keeppackages           true, false # default value: false
  mirrorlist             String
  mode                   String, Integer # default value: 0644
  path                   String
  priority               Integer # default value: 99
  refresh_cache          true, false # default value: true
  repo_name              String # default value: 'name' unless specified
  source                 String
  type                   String # default value: NONE
  action                 Symbol # defaults to :create if not specified
end

where:

  • zypper_repository is the resource.
  • name is the name given to the resource block.
  • action identifies which steps the chef-client will take to bring the node into the desired state.
  • autorefresh, baseurl, cookbook, description, enabled, gpgautoimportkeys, gpgcheck, gpgkey, keeppackages, mirrorlist, mode, path, priority, refresh_cache, repo_name, source, and type are the properties available to this resource.

Actions

The zypper_repository resource has the following actions:

:add

Default action. Add a new Zypper repository.

:remove

Remove a Zypper repository.

:refresh

Refresh a Zypper repository.

Properties

The zypper_repository resource has the following properties:

autorefresh

Ruby Type: true, false | Default Value: true

Determines whether or not the repository should be refreshed automatically.

baseurl

Ruby Type: String

The base URL for the Zypper repository, such as http://download.opensuse.org.

cookbook

Ruby Type: String

The cookbook to source the repository template file from. Only necessary if you’re not using the built in template.

description

Ruby Type: String

The description of the repository that will be shown by the zypper repos command.

enabled

Ruby Type: true, false | Default Value: true

Determines whether or not the repository should be enabled.

gpgautoimportkeys

Ruby Type: true, false | Default Value: true

Automatically import the specified key when setting up the repository.

gpgcheck

Ruby Type: true, false | Default Value: true

Determines whether or not to perform a GPG signature check on the repository.

gpgkey

Ruby Type: String

The location of the repository key to be imported.

keeppackages

Ruby Type: true, false | Default Value: false

Determines whether or not packages should be saved.

mirrorlist

Ruby Type: String

The URL of the mirror list that will be used.

mode

Ruby Type: String, Integer | Default Value: 0644

The file mode of the repository file.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
path

Ruby Type: String

The relative path from the repository’s base URL.

priority

Ruby Type: Integer | Default Value: 99

Determines the priority of the Zypper repository.

refresh_cache

Ruby Type: true, false | Default Value: true

Determines whether or not the package cache should be refreshed.

repo_name

Ruby Type: String | Default Value: 'name'

Specifies the repository name, if it differs from the resource name.

source

Ruby Type: String

The name of the template for the repository file. Only necessary if you’re not using the built in template.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
   mode '0600'
   owner 'root'
end

service 'nginx' do
   subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
type

Ruby Type: String | Default Value: NONE

Specifies the repository type.

Examples

Add a repository

This example adds the “Apache” repository for OpenSUSE Leap 42.2:

zypper_repository 'apache' do
  baseurl 'http://download.opensuse.org/repositories/Apache'
  path '/openSUSE_Leap_42.2'
  type 'rpm-md'
  priority '100'
end