Skip to main content

Resources Reference

This reference describes each of the resources available to Chef Infra 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

: This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra 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 attempts 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 Chef Infra 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 a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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 '/etc/some_config' do
  mode '0640'
  source 'some_config.erb'
  not_if 'some_app --check-config'
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 '/etc/some_app/some_config' do
  mode '0640'
  source 'some_config.erb'
  only_if { ::File.exist?('/etc/some_app/') }
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 Chef Infra 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 powershell_script 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 Chef Infra 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 Infra 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:

property_name lazy { code_block }

where lazy is used to tell Chef Infra 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 properties
  path '/foo/bar'
end

and a resource block that is doing lazy evaluation:

template 'template_name' do
  # some properties
  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 do
      { canvey_island: node.run_state['sea_power'] }
    end
  )
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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra 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 Infra 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 Chef Infra 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-elasticsearch]', :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 a Chef Infra 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

Chef Infra 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, Chef Infra 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 a Chef Infra 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 Chef Infra 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:

build_essential 'Install compilers' do
  action :nothing
end.run_action(:install)

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

This can be simplified by using the compile_time flag in Chef Infra Client 16 and later versions:

build_essential 'Install compilers' do
  compile_time true
end

That flag both forces the resource to run at compile time and sets the converge action to :nothing.

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

Using Custom Resources preferred to forcing to compile time

Compile time execution is often used to install gems before requiring them in recipe code.

This is a poor pattern since gems may depend on native gems which may require installing compilers at compile time.

build_essential 'Install compilers' do
  compile_time true
end

chef_gem 'aws-dsk' do
  compile_time true
end

require 'aws-sdk'

A better strategy is to move the code, which requires the gem, into a custom resource. Since all the actions of custom resources run at converge time, this defers requiring the gem until later in the overall Chef Infra Client execution. Unified mode can also be used in the resource to eliminate compile/converge mode issues entirely:

unified_mode true

action :run do
  build_essential 'Install compilers'

  chef_gem 'aws-sdk'

  require 'aws-sdk'
end

Download and parse a configuration file

A common use case is to download a configuration file, parse it, and then use the values in templates and to control other configuration.

An important distinction to make is that the downloaded configuration file only exists in a temporary state to be used by the Chef Infra Client. It will not be used directly by the system or applications that are managed by the Chef Infra Client.

To download and parse a JSON file and render it in a template, it makes sense to download the file during compile time:

  # the remote_file is being downloaded to a temporary file
  remote_file "#{Chef::Config[:file_cache_path]}/users.json" do
    source "https://jsonplaceholder.typicode.com/users"
    compile_time true
  end

  # this parsing needs to happen after the remote_file is downloaded, but will
  # be executed at compile time.
  array = JSON.parse(IO.read("#{Chef::Config[:file_cache_path]}/users.json")

  # the `array.last["phone"]` expression here will also be evaluated at compile
  # time and must be lazied via wrapping the expresssion in `lazy {}`
  file "/tmp/phone_number.txt" do
    content array.last["phone"]
  end

This is considerably cleaner than the alternative of lazy evaluating both the parsing of the JSON and the rendering of the data into the file template, which will happen if the remote_file resource is not run at compile time:

  # the execution of this is now deferred
  remote_file "#{Chef::Config[:file_cache_path]}/users.json" do
    source "https://jsonplaceholder.typicode.com/users"
  end

  # it is necessary due to lexical scoping issues to create this variable here
  array = nil

  # the parsing of the JSON is now deferred due to the ruby_block
  ruby_block "parse JSON" do
    block do
      array = JSON.parse(IO.read("#{Chef::Config[:file_cache_path]}/users.json")
    end
  end

  # the argument to the content property must now also be deferred
  file "/tmp/phone_number.txt" do
    content lazy { array.last["phone"] }
  end

This is an example of code that overuses deferred execution, uses more “lazy” evaluation, and is considerably harder to understand and write correctly.

Notifications will not work

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

execute 'ifconfig'

package 'vim-enhanced' do
  compile_time true
  notifies :run, 'execute[ifconfig]', :immediately
end

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.

The best approach to this problem is to use unified mode which eliminates the compile time and converge time distinction, while allowing notifications to work correctly.

Resources that are forced to compile time by default

The ohai_hint and hostname resources run at compile time by default.

This is due to the fact that later resources may consume the node attributes which are set by those resources leading to excessive use of lazy in subsequent resources (and similar issues to the remote_file example above).

The chef_gem resource used to execute at compile time by default, but now we recommend that users move code that executes at compile time to custom resources.

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, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra 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, Chef Infra 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; Chef Infra 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. The principal can be specified by either name or SID. When using 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. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the SDDL string constants. Chef Infra 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 TypeDescription
:applies_to_childrenSpecify 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_selfIndicates 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_deepIndicates 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, 'S-1-1-0'
  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, %w(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. Chef Infra 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, %w(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 Chef Infra 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, Chef Infra 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:

alternatives resource

alternatives resource page

The alternatives resource allows for configuration of command alternatives in Linux using the alternatives or update-alternatives packages.

New in Chef Infra Client 16.0.

Syntax


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

alternatives 'name' do
  link           String # default value: "/usr/bin/LINK_NAME"
  link_name      String # default value: 'name' unless specified
  path           String
  priority       String, Integer
  action         Symbol # defaults to :install if not specified
end

where:

  • alternatives is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • link, link_name, path, and priority are the properties available to this resource.

Actions


The alternatives resource has the following actions:

:auto
:install
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:refresh
:remove
:set

Properties


The alternatives resource has the following properties:

link
Ruby Type: String | Default Value: /usr/bin/LINK_NAME

The path to the alternatives link.

link_name
Ruby Type: String | Default Value: The resource block's name

The name of the link to create. This will be the command you type on the command line such as ruby or gcc.

path
Ruby Type: String

The absolute path to the original application binary such as /usr/bin/ruby27.

priority
Ruby Type: String, Integer

The priority of the alternative.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the alternatives resource in recipes:

Install an alternative:

alternatives 'python install 2' do
  link_name 'python'
  path '/usr/bin/python2.7'
  priority 100
  action :install
end

Set an alternative:

alternatives 'python set version 3' do
  link_name 'python'
  path '/usr/bin/python3'
  action :set
end

Set the automatic alternative state:

alternatives 'python auto' do
  link_name 'python'
  action :auto
end

Refresh an alternative:

alternatives 'python refresh' do
  link_name 'python'
  action :refresh
end

Remove an alternative:

alternatives 'python remove' do
  link_name 'python'
  path '/usr/bin/python3'
  action :remove
end

apt_package resource

apt_package resource page

Use the apt_package resource to manage packages on Debian and Ubuntu 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 of :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
  options                      String, Array
  overwrite_config_files       true, false # default value: false
  package_name                 String, Array
  response_file                String
  response_file_variables      Hash
  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 Chef Infra Client will take to bring the node into the desired state.
  • default_release, options, overwrite_config_files, package_name, response_file, response_file_variables, timeout, and version are the properties available to 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
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra 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.

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

An optional property to set the package name if it differs from the resource block’s name.

response_file
Ruby Type: String

The direct path to the file used to pre-seed a package.

response_file_variables
Ruby Type: Hash

A Hash of response file variables in the form of {‘VARIABLE’ => ‘VALUE’}.

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.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying 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 a Chef Infra 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 the apt_package resource in recipes:

Install a package using package manager:

apt_package 'name of package' do
  action :install
end

Install a package without specifying the default action:

apt_package 'name of package'

Install multiple packages at once:

apt_package %(package1 package2 package3)

Install without using recommend packages as a dependency:

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

apt_preference resource

apt_preference resource page

Use the apt_preference resource to create APT preference files. Preference files are used to control which package versions and sources are prioritized during installation.

New in Chef Infra Client 13.3.

Syntax


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

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 Chef Infra 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.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Removes the preferences file, thus unpinning the package.

Properties


The apt_preference resource has the following properties:

glob
Ruby Type: String

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

package_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the package name if it differs from the resource block’s name.

pin
Ruby Type: String | REQUIRED

The package version or repository to pin.

pin_priority
Ruby Type: String, Integer | REQUIRED

Sets the Pin-Priority for a package. See https://wiki.debian.org/AptPreferences for more details.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the apt_preference resource in recipes:

Pin libmysqlclient16 to a version 5.1.49-3:

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

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

Unpin a libmysqlclient16:

apt_preference 'libmysqlclient16' do
  action :remove
end

Pin all packages to prefer the packages.dotdeb.org repository:

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

apt_repository resource

apt_repository resource page

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

New in Chef Infra Client 12.9.

Syntax


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

apt_repository 'name' do
  arch               String, false
  cache_rebuild      true, false # default value: true
  components         Array # default value: `main` if using a PPA repository.
  cookbook           String, false
  deb_src            true, false # default value: false
  distribution       String, false # default value: The LSB codename of the node such as 'focal'.
  key                String, Array, false
  key_proxy          String, false
  keyserver          String, false # default value: "keyserver.ubuntu.com"
  repo_name          String # default value: 'name' unless specified
  trusted            true, false # default value: false
  uri                String
  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 Chef Infra Client will take to bring the node into the desired state.
  • arch, cache_rebuild, components, cookbook, deb_src, distribution, key, key_proxy, keyserver, repo_name, trusted, and uri are the properties available to this resource.

Actions


The apt_repository resource has the following actions:

:add
Default. Creates a repository file at /etc/apt/sources.list.d/ and builds the repository listing.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Removes the repository listing.

Properties


The apt_repository 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: `main` if using a PPA repository.

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: The LSB codename of the node such as 'focal'.

Usually a distribution’s codename, such as xenial, bionic, or focal.

key
Ruby Type: String, Array, false

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 | Default Value: The resource block's name

An optional property to set the repository name if it differs from the resource block’s name. The value of this setting must not contain spaces.

New in Chef Client 14.1

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.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the apt_repository resource in recipes:

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 'xenial-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 Ubuntu keyserver, and add source repo:

apt_repository 'juju' do
  uri 'ppa:juju/stable'
  components ['main']
  distribution 'xenial'
  key 'C8068B11'
  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 16.04 on AMD64:

apt_repository 'cloudera' do
  uri          'http://archive.cloudera.com/cdh4/ubuntu/xenial/amd64/cdh'
  arch         'amd64'
  distribution 'xenial-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

apt_update resource page

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

New in Chef Infra Client 12.7.

Syntax


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

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


The apt_update resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:periodic
Update the Apt repository at the interval specified by the frequency property.
:update
Update the Apt repository at the start of a Chef Infra Client run.

Properties


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


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the apt_update resource in recipes:

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 Infra Client run:

apt_update 'update'

archive_file resource

archive_file resource page

Use the archive_file resource to extract archive files to disk. This resource uses the libarchive library to extract multiple archive formats including tar, gzip, bzip, and zip formats.

New in Chef Infra Client 15.0.

Syntax


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

archive_file 'name' do
  destination      String
  group            String
  mode             String, Integer # default value: "755"
  options          Array, Symbol
  overwrite        true, false, auto # default value: false
  owner            String
  path             String # default value: 'name' unless specified
  action           Symbol # defaults to :extract if not specified
end

where:

  • archive_file is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • destination, group, mode, options, overwrite, owner, and path are the properties available to this resource.

Actions


The archive_file resource has the following actions:

:extract
Extract and archive file.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The archive_file resource has the following properties:

destination
Ruby Type: String | REQUIRED

The file path to extract the archive file to.

group
Ruby Type: String

The group of the extracted files.

mode
Ruby Type: String, Integer | Default Value: "755"

The mode of the extracted files. Integer values are deprecated as octal values (ex. 0755) would not be interpreted correctly.

options
Ruby Type: Array, Symbol | Default Value: lazy default

An array of symbols representing extraction flags. Example: :no_overwrite to prevent overwriting files on disk. By default, this properly sets :time which preserves the modification timestamps of files in the archive when writing them to disk.

overwrite
Ruby Type: true, false, auto | Default Value: false

Should the resource overwrite the destination file contents if they already exist? If set to :auto the date stamp of files within the archive will be compared to those on disk and disk contents will be overwritten if they differ. This may cause unintended consequences if disk date stamps are changed between runs, which will result in the files being overwritten during each client run. Make sure to properly test any change to this property.

owner
Ruby Type: String

The owner of the extracted files.

path
Ruby Type: String | Default Value: The resource block's name

An optional property to set the file path to the archive to extract if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the archive_file resource in recipes:

Extract a zip file to a specified directory:

archive_file 'Precompiled.zip' do
  path '/tmp/Precompiled.zip'
  destination '/srv/files'
end

Set specific permissions on the extracted files:

archive_file 'Precompiled.zip' do
  owner 'tsmith'
  group 'staff'
  mode '700'
  path '/tmp/Precompiled.zip'
  destination '/srv/files'
end

bash resource

bash resource page

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.

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
  path                       Array
  returns                    Integer, Array
  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 given to the resource block.
  • action identifies which steps Chef Infra 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 bash resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:run
Default. Run a script.

Properties


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

The current working directory from which the command will be 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.)

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.

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.

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


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the bash resource in recipes:

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

batch resource page

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.

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
  returns                    Integer, Array
  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 given to the resource block.
  • action identifies which steps Chef Infra 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


The batch resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:run
Run a batch file.

Properties


The batch 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, Chef Infra 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 | REQUIRED

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 the command will be 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.

interpreter
Ruby Type: String

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

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.

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


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the batch resource in recipes:

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

bff_package resource page

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. Chef Infra Client will still identify the correct provider to use based on the platform, regardless of the file extension.

Syntax


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

bff_package 'name' do
  options           String, Array
  package_name      String
  source            String
  timeout           String, Integer
  version           String
  action            Symbol # defaults to :install if not specified
end

where:

  • bff_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The bff_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:remove
Remove a package.

Properties


The bff_package resource has the following properties:

options
Ruby Type: String, Array

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

package_name
Ruby Type: String

An optional property to set the package name if it differs from the resource block’s name.

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.

timeout
Ruby Type: String, Integer

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

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the bff_package resource in recipes:

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, Chef Infra Client will identify the correct package provider. The following examples show how to install part of the IBM XL C/C++ compiler.

Installing 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

Installing 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

breakpoint resource page

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

New in Chef Infra Client 12.0.

Syntax


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

breakpoint 'name' do
  action      Symbol # defaults to :break if not specified
end

where:

  • breakpoint is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.

Actions


The breakpoint resource has the following actions:

:break
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra 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:

ModeDescription
StandaloneDefault. No cookbooks are loaded, and the run-list is empty.
Solochef-shell acts as a Chef Solo Client. It attempts to load the chef-solo configuration file at ~/.chef/config.rb and any JSON attributes passed. 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.
Clientchef-shell acts as a Chef Infra Client. During startup, it reads the Chef Infra Client configuration file from ~/.chef/client.rb and contacts the Chef Infra Server to get the node's run_list, attributes, and cookbooks. Chef Infra 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. If a NAMED_CONF is given, chef-shell will load ~/.chef/NAMED_CONF/chef_shell.rb
  3. If no NAMED_CONF is given chef-shell will load ~/.chef/chef_shell.rb if it exists
  4. If no chef_shell.rb can be found, chef-shell falls back to load:
    • /etc/chef/client.rb if -z option is given.
    • /etc/chef/solo.rb if –solo-legacy-mode option is given.
    • .chef/config.rb if -s option is given.
    • .chef/knife.rb if -s option is given.

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 Chef Infra Client. For example, to configure chef-shell to authenticate to the Chef Infra 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 Infra Client

By default, chef-shell loads in standalone mode and does not connect to the Chef Infra Server. The chef-shell can be run as a Chef Infra Client to verify functionality that is only available when Chef Infra Client connects to the Chef Infra 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 Infra 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 Infra Server, chef-shell can list, show, search for and edit cookbooks, clients, nodes, roles, environments, policyfiles, and data bags.

The syntax for managing objects on the Chef Infra 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

Where:

  • 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”, enter:

chef (preprod) > nodes.list

Which will 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}" }

will 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')

will return something similar to:

=> node[i-f09a939b]

Or:

chef (preprod) > load_balancer.ec2.public_hostname

will return something similar to:

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

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

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

You can also format the results with a code block. For example:

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

will 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

will 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 Infra 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 Infra 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 Chef Infra Client:

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

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

chef:recipe > chef_run.resume
  [Fri, 15 Jan 2020 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

You can rewind and step through a Chef Infra Client run:

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 2020 14:40:52 -0800] DEBUG: Processing file[/tmp/before-breakpoint]
  [Fri, 15 Jan 2020 14:40:52 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File
    => 1
  chef:recipe > chef_run.step
  [Fri, 15 Jan 2020 14:40:54 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new']
  [Fri, 15 Jan 2020 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 2020 14:40:56 -0800] DEBUG: Processing file[/tmp/after-breakpoint]
  [Fri, 15 Jan 2020 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, Chef Infra 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 your Chef Infra Client run to get the expected results:

chef:recipe > chef_run.rewind
  chef:recipe > chef_run.resume
  [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing file[/tmp/before-breakpoint]
  [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: file[/tmp/before-breakpoint] using Chef::Provider::File
  [Fri, 15 Jan 2020 14:48:56 -0800] INFO: Creating file[/tmp/before-breakpoint] at /tmp/before-breakpoint
  [Fri, 15 Jan 2020 14:48:56 -0800] DEBUG: Processing [./bin/../lib/chef/mixin/recipe_definition_dsl_core.rb:56:in 'new']
  [Fri, 15 Jan 2020 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 2020 14:49:20 -0800] DEBUG: Processing file[/tmp/after-breakpoint]
  [Fri, 15 Jan 2020 14:49:20 -0800] DEBUG: file[/tmp/after-breakpoint] using Chef::Provider::File
  [Fri, 15 Jan 2020 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.

Welcome to the chef-shell 15.8.23
For usage see https://docs.chef.io/chef_shell.html

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

chef (15.8.23)>

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
tracing is on
=> nil
chef >

and:

chef > tracing off
#0:(irb):2:Object:-: tracing off
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:109:Shell::Extensions::ObjectCoreExtensions:>:       def off
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:110:Shell::Extensions::ObjectCoreExtensions:-:         :off
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:111:Shell::Extensions::ObjectCoreExtensions:<:       end
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:272:main:>:       def tracing(on_or_off)
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:273:main:-:         conf.use_tracer = on_or_off.on_off_to_bool
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:162:Shell::Extensions::Symbol:>:       def on_off_to_bool
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:163:Shell::Extensions::Symbol:-:         to_s.on_off_to_bool
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:149:Shell::Extensions::String:>:       def on_off_to_bool
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:150:Shell::Extensions::String:-:         case self
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:154:Shell::Extensions::String:-:           false
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:158:Shell::Extensions::String:<:       end
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:164: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 Infra 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 Chef Infra Client is installed using RubyGems or a package manager, chef-shell should already be installed. When Chef Infra 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.

  Welcome to the chef-shell 15.8.23
  For usage see https://docs.chef.io/chef_shell.html

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

  chef (15.8.23)>

(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 a Chef Infra Client run, use the run_chef command:

chef:recipe_mode > run_chef
  [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: Processing file[/tmp/ohai2u_shef]
  [Fri, 15 Jan 2020 10:42:47 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File
  [Fri, 15 Jan 2020 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 Chef Infra Client again:

chef:recipe_mode > run_chef
  [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u_shef]
  [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u_shef] using Chef::Provider::File
  [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: Processing file[/tmp/ohai2u-again]
  [Fri, 15 Jan 2020 10:53:22 -0800] DEBUG: file[/tmp/ohai2u-again] using Chef::Provider::File
  [Fri, 15 Jan 2020 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, Chef Infra 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 the breakpoint resource in recipes:

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

In the following example, the name of each breakpoint is an arbitrary string.

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

In the previous examples, the names are used to indicate if the breakpoint is before or after a resource and also to specify which resource it is before or after.

build_essential resource

build_essential resource page

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

New in Chef Infra Client 14.0.

Syntax


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

build_essential 'name' do
  raise_if_unsupported      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 Chef Infra Client will take to bring the node into the desired state.
  • raise_if_unsupported 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:

build_essential

will behave the same as:

build_essential 'install tools'

Actions


The build_essential resource has the following actions:

:install
Default. Install the build essential packages.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:upgrade
Upgrade the Xcode CLI Tools on macOS hosts. New in Chef Infra Client 16

Properties


The build_essential resource has the following properties:

raise_if_unsupported
Ruby Type: true, false | Default Value: false

Raise a hard error on platforms where this resource is unsupported.

New in Chef Infra Client 15.5


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the build_essential resource in recipes:

Install compilation packages:

build_essential

Install compilation packages during the compilation phase:

build_essential 'Install compilation tools' do
  compile_time true
end

Upgrade compilation packages on macOS systems:

build_essential 'Install compilation tools' do
  action :upgrade
end

cab_package resource

cab_package resource page

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

New in Chef Infra Client 12.15.

Syntax


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

cab_package 'name' do
  options           String, Array
  package_name      String
  source            String # default value: The package name.
  timeout           String, Integer
  version           String
  action            Symbol # defaults to :install if not specified
end

where:

  • cab_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The cab_package resource has the following actions:

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

Properties


The cab_package resource has the following properties:

options
Ruby Type: String, Array

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

package_name
Ruby Type: String

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String | Default Value: The package name.

The local file path or URL for the CAB package.

timeout
Ruby Type: String, Integer

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

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the cab_package resource in recipes:

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

chef_acl resource page

Use the chef_acl resource to interact with access control lists (ACLs) that exist on the Chef Infra Server.

Syntax


The syntax for using the chef_acl resource in a recipe is as follows:

chef_acl 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_acl tells Chef Infra Client to use the Chef::Provider::ChefAcl provider during a Chef Infra Client run
  • name is the name of the resource block; when the path property is not specified as part of a recipe, name is also the name of the Chef Infra Client.
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_acl resource has the following actions:

:create
Default.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_acl resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines a chef-client completely. When true, any property not specified by this resource will be reset to default property values.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

path

A path to a directory in the chef-repo against which the ACL is applied. For example: nodes, nodes/*, nodes/my_node, */*, **, roles/base, data/secrets, cookbooks/apache2, /users/*, and so on.

raw_json

Chef Infra Client as JSON data. For example:

{
  "clientname": "client_name",
  "orgname": "org_name",
  "validator": false,
  "certificate": "-----BEGIN CERTIFICATE-----\n
                  ...
                  1234567890abcdefghijklmnopq\n
                  ...
                  -----END CERTIFICATE-----\n",
  "name": "node_name"
}

recursive

Use to apply changes to child objects. Use :on_change to apply changes to child objects only if the parent object changes. Set to true to apply changes even if the parent object does not change. Set to false to prevent any changes. Default value: :on_change.

remove_rights

Use to remove rights. For example:

remove_rights :read, :users => 'jkeiser', :groups => [ 'admins', 'users' ]

or:

remove_rights [ :create, :read ], :users => [ 'jkeiser', 'adam' ]

or:

remove_rights :all, :users => [ 'jkeiser', 'adam' ]

retries
Ruby Type: Integer | Default Value: 0

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

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

rights

Use to add rights. Syntax: :right, :right => 'user', :groups => [ 'group', 'group']. For example:

rights :read, :users => 'jkeiser', :groups => [ 'admins', 'users' ]

or:

rights [ :create, :read ], :users => [ 'jkeiser', 'adam' ]

or:

rights :all, :users => 'jkeiser'

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_client resource

chef_client resource page

Use the chef_client resource to create clients on your Chef Infra Server from within Chef Infra cookbook code.

Syntax


The syntax for using the chef_client resource in a recipe is as follows:

chef_client 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_client tells Chef Infra Client to use the Chef::Provider::ChefClient provider during a Chef Infra Client run
  • name is the name of the resource block; when the name property is not specified as part of a recipe, name is also the name of the Chef Infra Client
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_client resource has the following actions:

:create
Default. Use to create a chef-client.
:delete
Use to delete a chef-client.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:regenerate_keys
Use to regenerate the RSA public key for a chef-client.

Properties


The chef_client resource has the following properties:

admin

Use to specify whether Chef Infra Client is an API client.

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines a chef-client completely. When true, any property not specified by this resource will be reset to default property values.

ignore_failure
Ruby Type: true, false | Default Value: false

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

name

The name of Chef Infra Client.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

output_key_format

Use to specify the format of a public key. Possible values: pem, der, or openssh. Default value: openssh.

output_key_path

Use to specify the path to the location in which a public key will be written.

raw_json

Chef Infra Client as JSON data. For example:

{
  "clientname": "client_name",
  "orgname": "org_name",
  "validator": false,
  "certificate": "-----BEGIN CERTIFICATE-----\n
                  ...
                  1234567890abcdefghijklmnopq\n
                  ...
                  -----END CERTIFICATE-----\n",
  "name": "node_name"
}

retries
Ruby Type: Integer | Default Value: 0

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

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source_key

Use to copy a public or private key, but apply a different format and password. Use in conjunction with source_key_pass_phrase and source_key_path.

source_key_pass_phrase

The pass phrase for the public key. Use in conjunction with source_key and source_key_path.

source_key_path

The path to the public key. Use in conjunction with source_key and source_key_pass_phrase.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

validator

Use to specify if Chef Infra Client is a chef-validator.

Examples


This resource does not have any examples.

chef_client_config resource

chef_client_config resource page

Use the chef_client_config resource to create a client.rb file in the Chef Infra Client configuration directory. See the client.rb docs for more details on options available in the client.rb configuration file.

New in Chef Infra Client 16.6.

Syntax


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

chef_client_config 'name' do
  additional_config              String
  chef_license                   String
  chef_server_url                String
  config_directory               String
  event_loggers                  Array # default value: []
  exception_handlers             Array # default value: []
  file_backup_path               String
  file_cache_path                String
  file_staging_uses_destdir      String
  formatters                     Array # default value: []
  ftp_proxy                      String
  group                          String
  http_proxy                     String
  https_proxy                    String
  log_level                      Symbol
  log_location                   String, Symbol
  minimal_ohai                   true, false
  named_run_list                 String
  no_proxy                       String, Array # default value: []
  node_name                      String
  ohai_disabled_plugins          Array # default value: []
  ohai_optional_plugins          Array # default value: []
  pid_file                       String
  policy_group                   String
  policy_name                    String
  report_handlers                Array # default value: []
  ssl_verify_mode                Symbol, String
  start_handlers                 Array # default value: []
  user                           String
  action                         Symbol # defaults to :create if not specified
end

where:

  • chef_client_config is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • additional_config, chef_license, chef_server_url, config_directory, event_loggers, exception_handlers, file_backup_path, file_cache_path, file_staging_uses_destdir, formatters, ftp_proxy, group, http_proxy, https_proxy, log_level, log_location, minimal_ohai, named_run_list, no_proxy, node_name, ohai_disabled_plugins, ohai_optional_plugins, pid_file, policy_group, policy_name, report_handlers, ssl_verify_mode, start_handlers, and user are the properties available to this resource.

Actions


The chef_client_config resource has the following actions:

:create
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove

Properties


The chef_client_config resource has the following properties:

additional_config
Ruby Type: String

Additional text to add at the bottom of the client.rb config. This can be used to run custom Ruby or to add less common config options

chef_license
Ruby Type: String
Allowed Values: "accept", "accept-no-persist", "accept-silent"

Accept the Chef EULA

chef_server_url
Ruby Type: String | REQUIRED

The URL for the Chef Infra Server.

config_directory
Ruby Type: String | Default Value: `/etc/chef/` on *nix-like systems and `C:\chef\` on Windows

The directory to store the client.rb in.

event_loggers
Ruby Type: Array | Default Value: []

exception_handlers
Ruby Type: Array | Default Value: []

An array of hashes that contain a exception handler class and the arguments to pass to that class on initialization. The hash should include class and argument keys where class is a String and argument is an array of quoted String values. For example: [{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]

file_backup_path
Ruby Type: String

The location in which backup files are stored. If this value is empty, backup files are stored in the directory of the target file

file_cache_path
Ruby Type: String

The location in which cookbooks (and other transient data) files are stored when they are synchronized. This value can also be used in recipes to download files with the remote_file resource.

file_staging_uses_destdir
Ruby Type: String

How file staging (via temporary files) is done. When true, temporary files are created in the directory in which files will reside. When false, temporary files are created under ENV['TMP']

formatters
Ruby Type: Array | Default Value: []

ftp_proxy
Ruby Type: String

The proxy server to use for FTP connections.

group
Ruby Type: String

The group that should own the client.rb file and the configuration directory if it needs to be created. Note: The configuration directory will not be created if it already exists, which allows you to further control the setup of that directory outside of this resource.

http_proxy
Ruby Type: String

The proxy server to use for HTTP connections.

https_proxy
Ruby Type: String

The proxy server to use for HTTPS connections.

log_level
Ruby Type: Symbol
Allowed Values: :auto, :debug, :fatal, :info, :trace, :warn

The level of logging performed by the Chef Infra Client.

log_location
Ruby Type: String, Symbol

The location to save logs to. This can either by a path to a log file on disk :syslog to log to Syslog, :win_evt to log to the Windows Event Log, or 'STDERR'/'STDOUT' to log to the *nix text streams.

minimal_ohai
Ruby Type: true, false

Run a minimal set of Ohai plugins providing data necessary for the execution of Chef Infra Client’s built-in resources. Setting this to true will skip many large and time consuming data sets such as cloud or packages. Setting this this to true may break cookbooks that assume all Ohai data will be present.

named_run_list
Ruby Type: String

A specific named runlist defined in the node’s applied Policyfile, which the should be used when running Chef Infra Client.

no_proxy
Ruby Type: String, Array | Default Value: []

A comma-separated list or an array of URLs that do not need a proxy.

node_name
Ruby Type: String | Default Value: The `node.name` value reported by Chef Infra Client.

The name of the node. This configuration sets the node.name value used in cookbooks and the client_name value used when authenticating to a Chef Infra Server to determine what configuration to apply. Note: By default this configuration uses the node.name value which would be set during bootstrap. Hard coding this value in the client.rb config avoids logic within Chef Infra Server that performs DNS lookups and may fail in the event of a DNS outage. To skip this default value and instead use the built-in Chef Infra Server logic, set this property to nil

ohai_disabled_plugins
Ruby Type: Array | Default Value: []

Ohai plugins that should be disabled in order to speed up the Chef Infra Client run and reduce the size of node data sent to Chef Infra Client

ohai_optional_plugins
Ruby Type: Array | Default Value: []

Optional Ohai plugins that should be enabled to provide additional Ohai data for use in cookbooks.

pid_file
Ruby Type: String

The location in which a process identification number (pid) is saved. An executable, when started as a daemon, writes the pid to the specified file.

policy_group
Ruby Type: String

The name of a policy group that exists on the Chef Infra Server. policy_name must also be specified when setting this property.

policy_name
Ruby Type: String

The name of a policy, as identified by the name setting in a Policyfile.rb file. policy_group when setting this property.

report_handlers
Ruby Type: Array | Default Value: []

An array of hashes that contain a report handler class and the arguments to pass to that class on initialization. The hash should include class and argument keys where class is a String and argument is an array of quoted String values. For example: [{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]

ssl_verify_mode
Ruby Type: Symbol, String
Allowed Values: :verify_none, :verify_peer

Set the verify mode for HTTPS requests.

  • Use :verify_none for no validation of SSL certificates.
  • Use :verify_peer for validation of all SSL certificates, including the Chef Infra Server connections, S3 connections, and any HTTPS remote_file resource URLs used in Chef Infra Client runs. This is the recommended setting.

start_handlers
Ruby Type: Array | Default Value: []

An array of hashes that contain a report handler class and the arguments to pass to that class on initialization. The hash should include class and argument keys where class is a String and argument is an array of quoted String values. For example: [{'class' => 'MyHandler', %w('"argument1"', '"argument2"')}]

user
Ruby Type: String

The user that should own the client.rb file and the configuration directory if it needs to be created. Note: The configuration directory will not be created if it already exists, which allows you to further control the setup of that directory outside of this resource.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chef_client_config resource in recipes:

Bare minimum Chef Infra Client client.rb:

The absolute minimum configuration necessary for a node to communicate with the Infra Server is the URL of the Infra Server. All other configuration options either have values at the server side (Policyfiles, Roles, Environments, etc) or have default values determined at client startup.

chef_client_config 'Create client.rb' do
  chef_server_url 'https://chef.example.dmz'
end

More complex Chef Infra Client client.rb:

chef_client_config 'Create client.rb' do
  chef_server_url 'https://chef.example.dmz'
  log_level :info
  log_location :syslog
  http_proxy 'proxy.example.dmz'
  https_proxy 'proxy.example.dmz'
  no_proxy %w(internal.example.dmz)
end

Adding additional config content to the client.rb:

This resource aims to provide common configuration options. Some configuration options are missing and some users may want to use arbitrary Ruby code within their configuration. For this we offer an additional_config property that can be used to add any configuration or code to the bottom of the client.rb file. Also keep in mind that within the configuration directory is a client.d directory where you can put additional .rb files containing configuration options. These can be created using file or template resources within your cookbooks as necessary.

chef_client_config 'Create client.rb' do
  chef_server_url 'https://chef.example.dmz'
  additional_config <<~CONFIG
    # Extra config code to safely load a gem into the client run.
    # Since the config is Ruby you can run any Ruby code you want via the client.rb.
    # It's a great way to break things, so be careful
    begin
      require 'aws-sdk'
    rescue LoadError
      Chef::Log.warn "Failed to load aws-sdk."
    end
  CONFIG
end

Setup two report handlers in the client.rb:

chef_client_config 'Create client.rb' do
  chef_server_url 'https://chef.example.dmz'
  report_handlers [
    {
     'class' => 'ReportHandler1Class',
     'arguments' => ["'FirstArgument'", "'SecondArgument'"],
    },
    {
     'class' => 'ReportHandler2Class',
     'arguments' => ["'FirstArgument'", "'SecondArgument'"],
    },
  ]
end

chef_client_cron resource

chef_client_cron resource page

Use the chef_client_cron resource to setup the Chef Infra Client to run as a cron job. This resource will also create the specified log directory if it doesn’t already exist.

New in Chef Infra Client 16.0.

Syntax


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

chef_client_cron 'name' do
  accept_chef_license      true, false # default value: false
  append_log_file          true, false # default value: true
  chef_binary_path         String # default value: "/opt/chef/bin/chef-client"
  comment                  String
  config_directory         String # default value: "/etc/chef"
  daemon_options           Array
  day                      Integer, String # default value: "*"
  environment              Hash
  hour                     Integer, String # default value: "*"
  job_name                 String # default value: "chef-client"
  log_directory            String
  log_file_name            String # default value: "client.log"
  mailto                   String
  minute                   Integer, String # default value: "0,30"
  month                    Integer, String # default value: "*"
  nice                     Integer, String
  splay                    Integer, String # default value: 300
  user                     String # default value: "root"
  weekday                  Integer, String # default value: "*"
  action                   Symbol # defaults to :add if not specified
end

where:

  • chef_client_cron is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • accept_chef_license, append_log_file, chef_binary_path, comment, config_directory, daemon_options, day, environment, hour, job_name, log_directory, log_file_name, mailto, minute, month, nice, splay, user, and weekday are the properties available to this resource.

Actions


The chef_client_cron resource has the following actions:

:add
Add a cron job to run Chef Infra Client
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove a cron job for Chef Infra Client

Properties


The chef_client_cron resource has the following properties:

accept_chef_license
Ruby Type: true, false | Default Value: false

Accept the Chef Online Master License and Services Agreement. See https://www.chef.io/online-master-agreement/

append_log_file
Ruby Type: true, false | Default Value: true

Append to the log file instead of overwriting the log file on each run.

chef_binary_path
Ruby Type: String | Default Value: /opt/chef/bin/chef-client

The path to the chef-client binary.

comment
Ruby Type: String

A comment to place in the cron.d file.

config_directory
Ruby Type: String | Default Value: /etc/chef

The path of the config directory.

daemon_options
Ruby Type: Array

An array of options to pass to the chef-client command.

day
Ruby Type: Integer, String | Default Value: *

The day of month at which Chef Infra Client is to run (1 - 31) or a cron pattern such as ‘1,7,14,21,28’.

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

hour
Ruby Type: Integer, String | Default Value: *

The hour at which Chef Infra Client is to run (0 - 23) or a cron pattern such as ‘0,12’.

job_name
Ruby Type: String | Default Value: chef-client

The name of the cron job to create.

log_directory
Ruby Type: String | Default Value: /Library/Logs/Chef on macOS and /var/log/chef otherwise

The path of the directory to create the log file in.

log_file_name
Ruby Type: String | Default Value: client.log

The name of the log file to use.

mailto
Ruby Type: String

The e-mail address to e-mail any cron task failures to.

minute
Ruby Type: Integer, String | Default Value: 0,30

The minute at which Chef Infra Client is to run (0 - 59) or a cron pattern such as ‘0,30’.

month
Ruby Type: Integer, String | Default Value: *

The month in the year on which Chef Infra Client is to run (1 - 12, jan-dec, or *).

nice
Ruby Type: Integer, String

The process priority to run the chef-client process at. A value of -20 is the highest priority and 19 is the lowest priority.

New in Chef Infra Client 16.5

splay
Ruby Type: Integer, String | Default Value: 300

A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time.

user
Ruby Type: String | Default Value: root

The name of the user that Chef Infra Client runs as.

weekday
Ruby Type: Integer, String | Default Value: *

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


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chef_client_cron resource in recipes:

Setup Chef Infra Client to run using the default 30 minute cadence:

chef_client_cron 'Run Chef Infra Client as a cron job'

Run Chef Infra Client twice a day:

chef_client_cron 'Run Chef Infra Client every 12 hours' do
  minute 0
  hour '0,12'
end

Run Chef Infra Client with extra options passed to the client:

chef_client_cron 'Run an override recipe' do
  daemon_options ['--override-runlist mycorp_base::default']
end

chef_client_launchd resource

chef_client_launchd resource page

Use the chef_client_launchd resource to configure the Chef Infra Client to run on a schedule.

New in Chef Infra Client 16.5.

Syntax


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

chef_client_launchd 'name' do
  accept_chef_license      true, false # default value: false
  chef_binary_path         String # default value: "/opt/chef/bin/chef-client"
  config_directory         String # default value: "/etc/chef"
  daemon_options           Array
  environment              Hash
  interval                 Integer, String # default value: 30
  log_directory            String # default value: "/Library/Logs/Chef"
  log_file_name            String # default value: "client.log"
  low_priority_io          true, false # default value: true
  nice                     Integer, String
  splay                    Integer, String # default value: 300
  user                     String # default value: "root"
  working_directory        String # default value: "/var/root"
  action                   Symbol # defaults to :enable if not specified
end

where:

  • chef_client_launchd is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • accept_chef_license, chef_binary_path, config_directory, daemon_options, environment, interval, log_directory, log_file_name, low_priority_io, nice, splay, user, and working_directory are the properties available to this resource.

Actions


The chef_client_launchd resource has the following actions:

:disable
Disable running Chef Infra Client on a schedule using launchd
:enable
Enable running Chef Infra Client on a schedule using launchd
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_client_launchd resource has the following properties:

accept_chef_license
Ruby Type: true, false | Default Value: false

Accept the Chef Online Master License and Services Agreement. See https://www.chef.io/online-master-agreement/

chef_binary_path
Ruby Type: String | Default Value: /opt/chef/bin/chef-client

The path to the chef-client binary.

config_directory
Ruby Type: String | Default Value: /etc/chef

The path of the config directory.

daemon_options
Ruby Type: Array

An array of options to pass to the chef-client command.

environment
Ruby Type: Hash

A Hash containing additional arbitrary environment variables under which the launchd daemon will be run in the form of ({'ENV_VARIABLE' => 'VALUE'}).

interval
Ruby Type: Integer, String | Default Value: 30

Time in minutes between Chef Infra Client executions.

log_directory
Ruby Type: String | Default Value: /Library/Logs/Chef

The path of the directory to create the log file in.

log_file_name
Ruby Type: String | Default Value: client.log

The name of the log file to use.

low_priority_io
Ruby Type: true, false | Default Value: true

Run the chef-client process with low priority disk IO

nice
Ruby Type: Integer, String

The process priority to run the chef-client process at. A value of -20 is the highest priority and 19 is the lowest priority.

splay
Ruby Type: Integer, String | Default Value: 300

A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time.

user
Ruby Type: String | Default Value: root

The name of the user that Chef Infra Client runs as.

working_directory
Ruby Type: String | Default Value: /var/root

The working directory to run the Chef Infra Client from.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chef_client_launchd resource in recipes:

Set the Chef Infra Client to run on a schedule:

chef_client_launchd 'Setup the Chef Infra Client to run every 30 minutes' do
  interval 30
  action :enable
end

Disable the Chef Infra Client running on a schedule:

chef_client_launchd 'Prevent the Chef Infra Client from running on a schedule' do
  action :disable
end

chef_client_scheduled_task resource

chef_client_scheduled_task resource page

Use the chef_client_scheduled_task resource to setup the Chef Infra Client to run as a Windows scheduled task. This resource will also create the specified log directory if it doesn’t already exist.

New in Chef Infra Client 16.0.

Syntax


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

chef_client_scheduled_task 'name' do
  accept_chef_license      true, false # default value: false
  chef_binary_path         String # default value: "C:/opscode/chef/bin/chef-client"
  config_directory         String # default value: "/etc/chef"
  daemon_options           Array
  frequency                String # default value: "minute"
  frequency_modifier       Integer, String # default value: "30 if frequency is 'minute', 1 otherwise"
  log_directory            String # default value: "CONFIG_DIRECTORY/log"
  log_file_name            String # default value: "client.log"
  password                 String
  run_on_battery           true, false # default value: true
  splay                    Integer, String # default value: 300
  start_date               String
  start_time               String
  task_name                String # default value: "chef-client"
  user                     String # default value: "System"
  action                   Symbol # defaults to :add if not specified
end

where:

  • chef_client_scheduled_task is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • accept_chef_license, chef_binary_path, config_directory, daemon_options, frequency, frequency_modifier, log_directory, log_file_name, password, run_on_battery, splay, start_date, start_time, task_name, and user are the properties available to this resource.

Actions


The chef_client_scheduled_task resource has the following actions:

:add
Add a Windows Scheduled Task that runs Chef Infra Client.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove a Windows Scheduled Task that runs Chef Infra Client.

Properties


The chef_client_scheduled_task resource has the following properties:

accept_chef_license
Ruby Type: true, false | Default Value: false

Accept the Chef Online Master License and Services Agreement. See https://www.chef.io/online-master-agreement/

chef_binary_path
Ruby Type: String | Default Value: C:/opscode/chef/bin/chef-client

The path to the chef-client binary.

config_directory
Ruby Type: String | Default Value: /etc/chef

The path of the config directory.

daemon_options
Ruby Type: Array | Default Value: lazy default

An array of options to pass to the chef-client command.

frequency
Ruby Type: String | Default Value: minute
Allowed Values: "daily", "hourly", "minute", "monthly", "on_idle", "on_logon", "once", "onstart"

Frequency with which to run the task.

frequency_modifier
Ruby Type: Integer, String | Default Value: 30 if frequency is 'minute', 1 otherwise

Numeric value to go with the scheduled task frequency

log_directory
Ruby Type: String | Default Value: CONFIG_DIRECTORY/log

The path of the directory to create the log file in.

log_file_name
Ruby Type: String | Default Value: client.log

The name of the log file to use.

password
Ruby Type: String

The password for the user that Chef Infra Client runs as.

run_on_battery
Ruby Type: true, false | Default Value: true

Run the Chef Infra Client task when the system is on batteries.

splay
Ruby Type: Integer, String | Default Value: 300

A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time.

start_date
Ruby Type: String

The start date for the task in m:d:Y format (ex: 12/17/2020).

start_time
Ruby Type: String

The start time for the task in HH:mm format (ex: 14:00). If the frequency is minute default start time will be Time.now plus the frequency_modifier number of minutes.

task_name
Ruby Type: String | Default Value: chef-client

The name of the scheduled task to create.

user
Ruby Type: String | Default Value: System

The name of the user that Chef Infra Client runs as.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chef_client_scheduled_task resource in recipes:

Setup Chef Infra Client to run using the default 30 minute cadence:

chef_client_scheduled_task 'Run Chef Infra Client as a scheduled task'

Run Chef Infra Client on system start:

chef_client_scheduled_task 'Chef Infra Client on start' do
  frequency 'onstart'
end

Run Chef Infra Client with extra options passed to the client:

chef_client_scheduled_task 'Run an override recipe' do
  daemon_options ['--override-runlist mycorp_base::default']
end

Run Chef Infra Client daily at 01:00 am, specifying a named run-list:

chef_client_scheduled_task 'Run chef-client named run-list daily' do
  frequency 'daily'
  start_time '01:00'
  daemon_options ['-n audit_only']
end

chef_client_systemd_timer resource

chef_client_systemd_timer resource page

Use the chef_client_systemd_timer resource to setup the Chef Infra Client to run as a systemd timer.

New in Chef Infra Client 16.0.

Syntax


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

chef_client_systemd_timer 'name' do
  accept_chef_license      true, false # default value: false
  chef_binary_path         String # default value: "/opt/chef/bin/chef-client"
  config_directory         String # default value: "/etc/chef"
  cpu_quota                Integer, String
  daemon_options           Array
  delay_after_boot         String # default value: "1min"
  description              String # default value: "Chef Infra Client periodic execution"
  environment              Hash
  interval                 String # default value: "30min"
  job_name                 String # default value: "chef-client"
  run_on_battery           true, false # default value: true
  splay                    String # default value: "5min"
  user                     String # default value: "root"
  action                   Symbol # defaults to :add if not specified
end

where:

  • chef_client_systemd_timer is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • accept_chef_license, chef_binary_path, config_directory, cpu_quota, daemon_options, delay_after_boot, description, environment, interval, job_name, run_on_battery, splay, and user are the properties available to this resource.

Actions


The chef_client_systemd_timer resource has the following actions:

:add
Add a systemd timer that runs Chef Infra Client.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove a systemd timer that runs Chef Infra Client.

Properties


The chef_client_systemd_timer resource has the following properties:

accept_chef_license
Ruby Type: true, false | Default Value: false

Accept the Chef Online Master License and Services Agreement. See https://www.chef.io/online-master-agreement/

chef_binary_path
Ruby Type: String | Default Value: /opt/chef/bin/chef-client

The path to the chef-client binary.

config_directory
Ruby Type: String | Default Value: /etc/chef

The path of the config directory.

cpu_quota
Ruby Type: Integer, String

The systemd CPUQuota to run the chef-client process with. This is a percentage value of the total CPU time available on the system. If the system has more than 1 core this may be a value greater than 100.

New in Chef Infra Client 16.5

daemon_options
Ruby Type: Array

An array of options to pass to the chef-client command.

delay_after_boot
Ruby Type: String | Default Value: 1min

The time to wait after booting before the interval starts. This is expressed as a systemd time span such as 300seconds, 1hr, or 1m. See https://www.freedesktop.org/software/systemd/man/systemd.time.html for a complete list of allowed time span values.

description
Ruby Type: String | Default Value: Chef Infra Client periodic execution

The description to add to the systemd timer. This will be displayed when running systemctl status for the timer.

environment
Ruby Type: Hash

A Hash containing additional arbitrary environment variables under which the systemd timer will be run in the form of ({'ENV_VARIABLE' => 'VALUE'}).

interval
Ruby Type: String | Default Value: 30min

The interval to wait between executions. This is expressed as a systemd time span such as 300seconds, 1hr, or 1m. See https://www.freedesktop.org/software/systemd/man/systemd.time.html for a complete list of allowed time span values.

job_name
Ruby Type: String | Default Value: chef-client

The name of the system timer to create.

run_on_battery
Ruby Type: true, false | Default Value: true

Run the timer for Chef Infra Client if the system is on battery.

splay
Ruby Type: String | Default Value: 5min

A interval between 0 and X to add to the interval so that all chef-client commands don’t execute at the same time. This is expressed as a systemd time span such as 300seconds, 1hr, or 1m. See https://www.freedesktop.org/software/systemd/man/systemd.time.html for a complete list of allowed time span values.

user
Ruby Type: String | Default Value: root

The name of the user that Chef Infra Client runs as.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chef_client_systemd_timer resource in recipes:

Setup Chef Infra Client to run using the default 30 minute cadence:

chef_client_systemd_timer 'Run Chef Infra Client as a systemd timer'

Run Chef Infra Client every 1 hour:

chef_client_systemd_timer 'Run Chef Infra Client every 1 hour' do
  interval '1hr'
end

Run Chef Infra Client with extra options passed to the client:

chef_client_systemd_timer 'Run an override recipe' do
  daemon_options ['--override-runlist mycorp_base::default']
end

chef_client_trusted_certificate resource

chef_client_trusted_certificate resource page

Use the chef_client_trusted_certificate resource to add certificates to Chef Infra Client’s trusted certificate directory. This allows the Chef Infra Client to communicate with internal encrypted resources without errors.

New in Chef Infra Client 16.5.

Syntax


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

chef_client_trusted_certificate 'name' do
  cert_name        String # default value: 'name' unless specified
  certificate      String
  action           Symbol # defaults to :add if not specified
end

where:

  • chef_client_trusted_certificate is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • cert_name and certificate are the properties available to this resource.

Actions


The chef_client_trusted_certificate resource has the following actions:

:add
Add the trusted certificate
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove the trusted certificate

Properties


The chef_client_trusted_certificate resource has the following properties:

cert_name
Ruby Type: String | Default Value: The resource block's name

The name to use for the certificate file on disk. If not provided the name of the resource block will be used instead.

certificate
Ruby Type: String | REQUIRED

The text of the certificate file including the BEGIN/END comment lines.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chef_client_trusted_certificate resource in recipes:

Trust a self signed certificate:

chef_client_trusted_certificate 'self-signed.badssl.com' do
  certificate <<~CERT
  -----BEGIN CERTIFICATE-----
  MIIDeTCCAmGgAwIBAgIJAPziuikCTox4MA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV
  BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNp
  c2NvMQ8wDQYDVQQKDAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTAeFw0x
  OTEwMDkyMzQxNTJaFw0yMTEwMDgyMzQxNTJaMGIxCzAJBgNVBAYTAlVTMRMwEQYD
  VQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ8wDQYDVQQK
  DAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTCCASIwDQYJKoZIhvcNAQEB
  BQADggEPADCCAQoCggEBAMIE7PiM7gTCs9hQ1XBYzJMY61yoaEmwIrX5lZ6xKyx2
  PmzAS2BMTOqytMAPgLaw+XLJhgL5XEFdEyt/ccRLvOmULlA3pmccYYz2QULFRtMW
  hyefdOsKnRFSJiFzbIRMeVXk0WvoBj1IFVKtsyjbqv9u/2CVSndrOfEk0TG23U3A
  xPxTuW1CrbV8/q71FdIzSOciccfCFHpsKOo3St/qbLVytH5aohbcabFXRNsKEqve
  ww9HdFxBIuGa+RuT5q0iBikusbpJHAwnnqP7i/dAcgCskgjZjFeEU4EFy+b+a1SY
  QCeFxxC7c3DvaRhBB0VVfPlkPz0sw6l865MaTIbRyoUCAwEAAaMyMDAwCQYDVR0T
  BAIwADAjBgNVHREEHDAaggwqLmJhZHNzbC5jb22CCmJhZHNzbC5jb20wDQYJKoZI
  hvcNAQELBQADggEBAGlwCdbPxflZfYOaukZGCaxYK6gpincX4Lla4Ui2WdeQxE95
  w7fChXvP3YkE3UYUE7mupZ0eg4ZILr/A0e7JQDsgIu/SRTUE0domCKgPZ8v99k3A
  vka4LpLK51jHJJK7EFgo3ca2nldd97GM0MU41xHFk8qaK1tWJkfrrfcGwDJ4GQPI
  iLlm6i0yHq1Qg1RypAXJy5dTlRXlCLd8ufWhhiwW0W75Va5AEnJuqpQrKwl3KQVe
  wGj67WWRgLfSr+4QG1mNvCZb2CkjZWmxkGPuoP40/y7Yu5OFqxP5tAjj4YixCYTW
  EVA0pmzIzgBg+JIe3PdRy27T0asgQW/F4TY61Yk=
  -----END CERTIFICATE-----
  CERT
end

chef_container resource

chef_container resource page

Use the chef_container resource to interact with container objects that exist on the Chef Infra Server.

Syntax


The syntax for using the chef_container resource in a recipe is as follows:

chef_container 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_container tells Chef Infra Client to use the Chef::Provider::ChefContainer provider during a Chef Infra Client run
  • name is the name of the resource block
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_container resource has the following actions:

:create
Default.
:delete
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_container resource has the following properties:

chef_server

The URL for the Chef Infra Server.

ignore_failure
Ruby Type: true, false | Default Value: false

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

name

The name of the container.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

retries
Ruby Type: Integer | Default Value: 0

The number of attempts 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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_data_bag resource

chef_data_bag resource page

Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search.

Use the chef_data_bag resource to manage data bags.

Syntax


The syntax for using the chef_data_bag resource in a recipe is as follows:

chef_data_bag 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_data_bag tells Chef Infra Client to use the Chef::Provider::ChefDataBag provider during a Chef Infra Client run
  • name is the name of the resource block and also the name of the data bag
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_data_bag resource has the following actions:

:create
Default. Use to create a data bag.
:delete
Use to delete a data bag.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_data_bag resource has the following properties:

chef_server

The URL for the Chef Infra Server.

ignore_failure
Ruby Type: true, false | Default Value: false

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

name

The name of the data bag.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

retries
Ruby Type: Integer | Default Value: 0

The number of attempts 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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_data_bag_item resource

chef_data_bag_item resource page

A data bag is a container of related data bag items, where each individual data bag item is a JSON file. knife can load a data bag item by specifying the name of the data bag to which the item belongs and then the filename of the data bag item. The only structural requirement of a data bag item is that it must have an id:

{
  /* This is a supported comment style */
  // This style is also supported
  "id": "ITEM_NAME",
  "key": "value"
}

where

  • key and value are the key:value pair for each additional attribute within the data bag item
  • /* ... */ and // ... show two ways to add comments to the data bag item

Use the chef_data_bag_item resource to manage data bag items.

Syntax


The syntax for using the chef_data_bag_item resource in a recipe is as follows:

chef_data_bag_item 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_data_bag_item tells Chef Infra Client to use the Chef::Provider::ChefDataBagItem provider during a Chef Infra Client run
  • name is the name of the resource block and also the name of the data bag item
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_data_bag_item resource has the following actions:

:create
Default. Use to create a data bag item.
:delete
Use to delete a data bag item.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_data_bag_item resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines a data bag item completely. When true, any property not specified by this resource will be reset to default property values.

encrypt

Use to specify whether encryption is used for a data bag item.

encryption_version

The minimum required version of data bag encryption. Possible values: 0, 1, and 2. When all of the machines in an organization are running chef-client version 11.6 (or higher), it is recommended that this value be set to 2.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

raw_data

Use to create a data bag from a local file from ./data_bags/bag_name/file.

raw_json

The data bag item as JSON data. For example:

{
  "id": "adam",
  "real_name": "Adam Brent Jacob"
}

retries
Ruby Type: Integer | Default Value: 0

The number of attempts 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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_environment resource

chef_environment resource page

An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production.

Use the chef_environment resource to manage environments.

Syntax


The syntax for using the chef_environment resource in a recipe is as follows:

chef_environment 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_environment tells Chef Infra Client to use the Chef::Provider::ChefEnvironment provider during a Chef Infra Client run
  • name is the name of the resource block; when the name property is not specified as part of a recipe, name is also the name of the environment
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_environment resource has the following actions:

:create
Default. Use to create an environment.
:delete
Use to delete an environment.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_environment resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines an environment completely. When true, any property not specified by this resource will be reset to default property values.

cookbook_versions

The cookbook versions used with the environment. Default value: {}.

default_attributes

A default attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use default attributes as often as possible in cookbooks.

Default value: {}.

description

The description of the environment. This value populates the description field for the environment on the Chef Infra Server.

ignore_failure
Ruby Type: true, false | Default Value: false

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

name

The name of the environment.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

override_attributes

An override attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than default, force_default, and normal attributes. An override attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses override attributes only when required.

Default value: {}.

raw_json

The environment as JSON data. For example:

{
  "name":"backend",
  "description":"",
  "cookbook_versions":{},
  "json_class":"Chef::Environment",
  "chef_type":"environment",
  "default_attributes":{},
  "override_attributes":{}
}

retries
Ruby Type: Integer | Default Value: 0

The number of attempts 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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_gem resource

chef_gem resource page

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.

Warning

The chef_gem and gem_package resources are both used to install Ruby gems. For any machine on which Chef Infra 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 Chef Infra Client. Use the chef_gem resource to install gems into the instance of Ruby that is dedicated to Chef Infra Client. Use the gem_package resource to install all other gems (i.e. install gems system-wide).

Syntax


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
  gem_binary                  String
  include_default_source      true, false
  options                     String, Hash, Array
  package_name                String
  source                      String, Array
  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 Chef Infra Client will take to bring the node into the desired state.
  • clear_sources, gem_binary, include_default_source, options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The chef_gem resource has the following actions:

:install
Default. Install a gem. If a version is specified, install the specified version of the gem.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra 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).

gem_binary
Ruby Type: String | Default Value: The `gem` binary included with Chef Infra Client.

The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by Chef Infra Client will be used.

include_default_source
Ruby Type: true, false

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

New in Chef Client 13.0

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

An optional property to set the package name if it differs from the resource block’s name.

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.

timeout
Ruby Type: String, Integer

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

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chef_gem resource in recipes:

Compile time vs. converge time installation of gems

To install a gem while Chef Infra Client is configuring the node (the converge phase), set the compile_time property to false:

chef_gem 'loofah' 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 'loofah' do
  compile_time true
  action :install
end

Install MySQL gem into Chef Infra Client*

apt_update

build_essential 'install compilation tools' do
  compile_time true
end

chef_gem 'mysql'

chef_group resource

chef_group resource page

Use the chef_group resource to interact with group objects that exist on the Chef server.

Syntax


The syntax for using the chef_group resource in a recipe is as follows:

chef_group 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_group tells Chef Infra Client to use the Chef::Provider::ChefGroup provider during a Chef Infra Client run
  • name is the name of the resource block
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_group resource has the following actions:

:create
Default.
:delete
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_group resource has the following properties:

chef_server

The URL for the Chef server.

clients

complete

Use to specify if this resource defines a chef-client completely. When true, any property not specified by this resource will be reset to default property values.

groups

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

raw_json

The group as JSON data. For example:

{
  :groupname => "chef"
}

remove_clients

remove_groups

remove_users

retries
Ruby Type: Integer | Default Value: 0

The number of attempts 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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

users

Examples


This resource does not have any examples.

chef_handler resource

chef_handler resource page

Use the chef_handler resource to enable handlers during a Chef Infra Client run. The resource allows arguments to be passed to Chef Infra Client, which then applies the conditions defined by the custom handler to the node attribute data collected during a Chef Infra 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 Infra Client run.

New in Chef Infra Client 14.0.

Handler Types

There are three types of handlers:

HandlerDescription
exceptionAn exception handler is used to identify situations that have caused a Chef Infra Client run to fail. An exception handler can be loaded at the start of a Chef Infra 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.
reportA report handler is used when a Chef Infra Client run succeeds and reports back on certain details about that Chef Infra Client run. A report handler can be loaded at the start of a Chef Infra 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.
startA start handler is used to run events at the beginning of a Chef Infra Client run. A start handler can be loaded at the start of a Chef Infra 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 Infra Client run.

  • An exception handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run fails.
  • A report handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run is successful.

Both types of handlers can be used to gather data about a Chef Infra 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 a Chef Infra 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 a Chef Infra 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 a Chef Infra 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 Chef Infra Client prior to the start of a Chef Infra Client run. Use the chef-client cookbook to install the start handler.

Start handlers are made available to a Chef Infra 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 Chef Infra Client at the start of a Chef Infra 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.override['chef_client']['load_gems']['chef-reporting'] = {
  require_name: 'chef_reporting',
  action: :install,
}

node.override['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, Hash
  class_name      String # default value: 'name' unless specified
  source          String
  type            Hash # default value: {"report"=>true, "exception"=>true}
  action          Symbol # defaults to :enable if not specified
end

where:

  • chef_handler is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • arguments, class_name, source, and type are the properties available to 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
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_handler resource has the following properties:

arguments
Ruby Type: Array, Hash

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 | Default Value: The resource block's name

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

source
Ruby Type: String

The full path to the handler file. Can also be a gem path if the handler ships as part of a Ruby gem.

type
Ruby Type: Hash | Default Value: {"report"=>true, "exception"=>true}

The type of handler to register as, i.e. :report, :exception or both.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

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 Chef Infra 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 Infra Client run fails:

require 'net/smtp'

module OrgName
  class SendEmail < Chef::Handler
    def report
      if run_status.failed?
        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. Chef Infra 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 Chef Infra 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 a Chef Infra 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 Chef Infra Client before the report interface is run for any handler. The run_status object keeps track of the status of a Chef Infra Client run and will contain some (or all) of the following properties:

PropertyDescription
all_resourcesA list of all resources that are included in the resource_collection property for the current Chef Infra Client run.
backtraceA backtrace associated with the uncaught exception data that caused a Chef Infra Client run to fail, if present; nil for a successful Chef Infra Client run.
elapsed_timeThe amount of time between the start (start_time) and end (end_time) of a Chef Infra Client run.
end_timeThe time at which a Chef Infra Client run ended.
exceptionThe uncaught exception data which caused a Chef Infra Client run to fail; nil for a successful Chef Infra Client run.
failed?Show that a Chef Infra Client run has failed when uncaught exceptions were raised during a Chef Infra Client run. An exception handler runs when the failed? indicator is true.
nodeThe node on which a Chef Infra Client run occurred.
run_contextAn instance of the Chef::RunContext object; used by Chef Infra Client to track the context of the run; provides access to the cookbook_collection, resource_collection, and definitions properties.
start_timeThe time at which a Chef Infra Client run started.
success?Show that a Chef Infra Client run succeeded when uncaught exceptions were not raised during a Chef Infra Client run. A report handler runs when the success? indicator is true.
updated_resourcesA list of resources that were marked as updated as a result of a Chef Infra Client run.

Note

These properties are not always available. For example, a start handler runs at the beginning of Chef Infra 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 the chef_handler resource in recipes:

Enable the ‘MyHandler’ handler

The following example shows how to enable a fictional ‘MyHandler’ handler which is located on disk at /etc/chef/my_handler.rb. The handler will be configured to run with Chef Infra Client and will be passed values to the handler’s initializer method:

chef_handler 'MyHandler' do
  source '/etc/chef/my_handler.rb' # the file should already be at this path
  arguments path: '/var/chef/reports'
  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 :enable
  compile_time true
end

Handle only exceptions

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

Cookbook Versions (a custom handler)

@juliandunn created a custom report handler that logs all of the cookbooks and cookbook versions that were used during a Chef Infra Client run, and then reports after the run is complete.

cookbook_versions.rb:

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

require 'chef/log'

module Chef
  class CookbookVersionsHandler < Chef::Handler
    def report
      cookbooks = run_context.cookbook_collection
      Chef::Log.info('Cookbooks and versions run: #{cookbooks.map {|x| x.name.to_s + ' ' + 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 Infra Client run.

cookbook_file '/etc/chef/cookbook_versions.rb' do
  source 'cookbook_versions.rb'
  action :create
end

chef_handler 'Chef::CookbookVersionsHandler' do
  source '/etc/chef/cookbook_versions.rb'
  type report: true
  action :enable
end

This recipe will generate report output similar to the following:

[2013-11-26T03:11:06+00:00] INFO: Chef Infra Client 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: ["cookbook_versions_handler 1.0.0"]
[2013-11-26T03:11:06+00:00] INFO: Report handlers complete

JsonFile Handler

The JsonFile 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 Chef Infra 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 ErrorReport Handler is built into Chef Infra 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 Chef Infra 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

chef_node resource

chef_node resource page

A node is any device—physical, virtual, cloud, network device, etc.—that is under management by Chef Infra.

Use the chef_node resource to manage nodes.

Syntax


The syntax for using the chef_node resource in a recipe is as follows:

chef_node 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_node tells Chef Infra Client to use the Chef::Provider::ChefNode provider during a Chef Infra Client run
  • name is the name of the resource block
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_node resource has the following actions:

:create
Default. Use to create a node.
:delete
Use to delete a node.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_node resource has the following properties:

automatic_attributes

An automatic attribute contains data that is identified by Ohai at the beginning of every Chef Infra Client run. An automatic attribute cannot be modified and always has the highest attribute precedence.

Default value: {}.

chef_environment

The Chef Infra Server environment in which this node should exist (or does exist).

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines a node completely. When true, any property not specified by this resource will be reset to default property values.

default_attributes

A default attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use default attributes as often as possible in cookbooks.

Default value: {}.

ignore_failure
Ruby Type: true, false | Default Value: false

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

name

The unique identifier of the node.

normal_attributes

A normal attribute is a setting that persists in the node object. A normal attribute has a higher attribute precedence than a default attribute.

Default value: {}.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

override_attributes

An override attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than default, force_default, and normal attributes. An override attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses override attributes only when required.

Default value: {}.

raw_json

The node as JSON data. For example:

{
  "overrides": {},
  "name": "latte",
  "chef_type": "node",
  "json_class": "Chef::Node",
  "attributes": {
    "hardware_type": "laptop"
  },
  "run_list": [
    "recipe[apache2]"
  ],
  "defaults": {}
}

retries
Ruby Type: Integer | Default Value: 0

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

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

run_list

A comma-separated list of roles and/or recipes to be applied. Default value: []. For example: ["recipe[default]","recipe[apache2]"]

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_organization resource

chef_organization resource page

Use the chef_organization resource to interact with organization objects that exist on the Chef Infra Server.

Syntax


The syntax for using the chef_organization resource in a recipe is as follows:

chef_organization 'name' do
  attribute 'value' # see attributes section below
  ...
  action :action # see actions section below
end

where:

  • chef_organization tells Chef Infra Client to use the Chef::Provider::ChefOrganization provider during a Chef Infra Client run
  • name is the name of the resource block
  • attribute is zero (or more) of the attributes that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_organization resource has the following actions:

:create
Default.
:delete
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_organization resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines an organization completely. When true, any property not specified by this resource will be reset to default property values.

full_name

The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: Chef Software, Inc..

ignore_failure
Ruby Type: true, false | Default Value: false

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

invites

Use to specify a list of users to be invited to the organization. An invitation is sent to any user in this list who is not already a member of the organization.

members

Use to specify a list of users who MUST be members of the organization. These users will be added directly to the organization. The user who initiates this operation MUST also have permission to add users to the specified organization.

members_specified

Use to discover if a user is a member of an organization. Will return true if the user is a member.

name

The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: chef.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

raw_json

The organization as JSON data. For example:

{
  "name": "chef",
  "full_name": "Chef Software, Inc",
  "guid": "f980d1asdfda0331235s00ff36862
  ...
}

remove_members

Use to remove the specified users from an organization. Invitations that have not been accepted will be cancelled.

retries
Ruby Type: Integer | Default Value: 0

The number of attempts 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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_role resource

chef_role resource page

A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role.

Use the chef_role resource to manage roles.

Syntax


The syntax for using the chef_role resource in a recipe is as follows:

chef_role 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_role tells Chef Infra Client to use the Chef::Provider::ChefRole provider during a Chef Infra Client run
  • name is the name of the resource block; when the name property is not specified as part of a recipe, name is also the name of the role
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_role resource has the following actions:

:create
Default. Use to create a role.
:delete
Use to delete a role.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_role resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines a role completely. When true, any property not specified by this resource will be reset to default property values.

default_attributes

A default attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use default attributes as often as possible in cookbooks.

Default value: {}.

description

The description of the role. This value populates the description field for the role on the Chef Infra Server.

env_run_lists

The environment-specific run-list for a role. Default value: []. For example: ["env_run_lists[webserver]"]

ignore_failure
Ruby Type: true, false | Default Value: false

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

name

The name of the role.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

override_attributes

An override attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than default, force_default, and normal attributes. An override attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses override attributes only when required.

Default value: {}.

raw_json

The role as JSON data. For example:

{
  "name": "webserver",
  "chef_type": "role",
  "json_class": "Chef::Role",
  "default_attributes": {},
  "description": "A webserver",
  "run_list": [
    "recipe[apache2]"
  ],
  "override_attributes": {}
}

retries
Ruby Type: Integer | Default Value: 0

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

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

run_list

A comma-separated list of roles and/or recipes to be applied. Default value: []. For example: ["recipe[default]","recipe[apache2]"]

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_sleep resource

chef_sleep resource page

Use the chef_sleep resource to pause (sleep) for a number of seconds during a Chef Infra Client run. Only use this resource when a command or service exits successfully but is not ready for the next step in a recipe.

New in Chef Infra Client 15.5.

Syntax


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

chef_sleep 'name' do
  seconds      String, Integer # default value: 'name' unless specified
  action       Symbol # defaults to :sleep if not specified
end

where:

  • chef_sleep is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • seconds is the property available to this resource.

Actions


The chef_sleep resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:sleep
Pause the Chef Infra Client run for a specified number of seconds.

Properties


The chef_sleep resource has the following properties:

seconds
Ruby Type: String, Integer | Default Value: The resource block's name

The number of seconds to sleep.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chef_sleep resource in recipes:

Sleep for 10 seconds:

chef_sleep '10'

Sleep for 10 seconds with a descriptive resource name for logging:

chef_sleep 'wait for the service to start' do
  seconds 10
end

Use a notification from another resource to sleep only when necessary:

service 'Service that is slow to start and reports as started' do
  service_name 'my_database'
  action :start
  notifies :sleep, chef_sleep['wait for service start']
end

chef_sleep 'wait for service start' do
  seconds 30
  action :nothing
end

chef_user resource

chef_user resource page

Use the chef_user resource to manage users.

Syntax


The syntax for using the chef_user resource in a recipe is as follows:

chef_user 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_user tells Chef Infra Client to use the Chef::Provider::ChefUser provider during a Chef Infra Client run
  • name is the name of the resource block; when the name property is not specified as part of a recipe, name is also the name of the user
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_user resource has the following actions:

:create
Default. Use to create a user.
:delete
Use to delete a user.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_user resource has the following properties:

admin

Create a client as an admin client. This is required for any user to access Chef as an administrator.

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines a user completely. When true, any property not specified by this resource will be reset to default property values.

email

The email address for the user.

external_authentication_uid

ignore_failure
Ruby Type: true, false | Default Value: false

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

name

The name of the user.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

output_key_format

Use to specify the format of a public key. Possible values: pem, der, or openssh. Default value: openssh.

output_key_path

Use to specify the path to the location in which a public key will be written.

raw_json

The user as JSON data. For example:

{
  "name": "Robert Forster"
}

recovery_authentication_enabled

retries
Ruby Type: Integer | Default Value: 0

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

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source_key

Use to copy a public or private key, but apply a different format and password. Use in conjunction with source_key_pass_phrase and source_key_path.

source_key_pass_phrase

The pass phrase for the public key. Use in conjunction with source_key and source_key_path.

source_key_path

The path to the public key. Use in conjunction with source_key and source_key_pass_phrase.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_vault_secret resource

chef_vault_secret resource page

Use the chef_vault_secret resource to store secrets in Chef Vault items. Where possible and relevant, this resource attempts to map behavior and functionality to the knife vault sub-commands.

New in Chef Infra Client 16.0.

Syntax


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

chef_vault_secret 'name' do
  admins           String, Array
  clients          String, Array
  data_bag         String
  environment      String
  id               String # default value: 'name' unless specified
  raw_data         Hash, ChefUtils::Mash # default value: {}
  search           String # default value: "*:*"
  action           Symbol # defaults to :create if not specified
end

where:

  • chef_vault_secret is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • admins, clients, data_bag, environment, id, raw_data, and search are the properties available to this resource.

Actions


The chef_vault_secret resource has the following actions:

:create
Create a Chef Vault data bag.
:create_if_missing
Create a Chef Vault data bag unless it already exists.
:delete
Delete a Chef Vault data bag if present.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_vault_secret resource has the following properties:

admins
Ruby Type: String, Array | REQUIRED

A list of admin users who should have access to the item. Corresponds to the ‘admin’ option when using the chef-vault knife plugin. Can be specified as a comma separated string or an array.

clients
Ruby Type: String, Array

A search query for the nodes' API clients that should have access to the item.

data_bag
Ruby Type: String | REQUIRED

The data bag that contains the item.

environment
Ruby Type: String

The Chef environment of the data if storing per environment values.

id
Ruby Type: String | Default Value: The resource block's name

The name of the data bag item if it differs from the name of the resource block

raw_data
Ruby Type: Hash, ChefUtils::Mash | Default Value: {}

The raw data, as a Ruby Hash, that will be stored in the item.

search
Ruby Type: String | Default Value: *:*

Search query that would match the same used for the clients, gets stored as a field in the item.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chef_vault_secret resource in recipes:

To create a ‘foo’ item in an existing ‘bar’ data bag:

chef_vault_secret 'foo' do
  data_bag 'bar'
  raw_data({ 'auth' => 'baz' })
  admins 'jtimberman'
  search '*:*'
end

To allow multiple admins access to an item:

chef_vault_secret 'root-password' do
  admins 'jtimberman,paulmooring'
  data_bag 'secrets'
  raw_data({ 'auth' => 'DoNotUseThisPasswordForRoot' })
  search '*:*'
end

chocolatey_config resource

chocolatey_config resource page

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

New in Chef Infra Client 14.3.

Syntax


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

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 Chef Infra 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:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:set
Default. Sets a Chocolatey config value.
:unset
Unsets a Chocolatey config value.

Properties


The chocolatey_config resource has the following properties:

config_key
Ruby Type: String | Default Value: The resource block's name

An optional property to set the config key name if it differs from the resource block’s name.

value
Ruby Type: String

The value to set.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chocolatey_config resource in recipes:

Set the Chocolatey cacheLocation config:

chocolatey_config 'Set cacheLocation config' do
  config_key 'cacheLocation'
  value 'C:	empoco'
end

Unset a Chocolatey config:

chocolatey_config 'BogusConfig' do
  action :unset
end

chocolatey_feature resource

chocolatey_feature resource page

Use the chocolatey_feature resource to enable and disable Chocolatey features.

New in Chef Infra Client 15.1.

Syntax


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

chocolatey_feature 'name' do
  feature_name      String # default value: 'name' unless specified
  action            Symbol # defaults to :enable if not specified
end

where:

  • chocolatey_feature is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • feature_name is the property available to this resource.

Actions


The chocolatey_feature resource has the following actions:

:disable
Disable a Chocolatey Feature.
:enable
Enable a Chocolatey Feature.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chocolatey_feature resource has the following properties:

feature_name
Ruby Type: String | Default Value: The resource block's name

The name of the Chocolatey feature to enable or disable.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chocolatey_feature resource in recipes:

Enable the checksumFiles Chocolatey feature

chocolatey_feature 'checksumFiles' do
  action :enable
end

Disable the checksumFiles Chocolatey feature

chocolatey_feature 'checksumFiles' do
  action :disable
end

chocolatey_package resource

chocolatey_package resource page

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.

Note

The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the Chocolatey cookbook to your node’s run list.

New in Chef Infra 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
  list_options      String
  options           String, Array
  package_name      String, Array
  password          String
  returns           Integer, Array # default value: [0, 2]
  source            String
  timeout           String, Integer
  user              String
  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 Chef Infra Client will take to bring the node into the desired state.
  • list_options, options, package_name, password, returns, source, timeout, user, and version are the properties available to this resource.

Actions


The chocolatey_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra 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:

list_options
Ruby Type: String

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

New in Chef Infra Client 15.3

options
Ruby Type: String, Array

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.

password
Ruby Type: String

The password to authenticate to the source.

New in Chef Infra Client 15.3

returns
Ruby Type: Integer, Array | Default Value: [0, 2]

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

0: operation was successful, no issues detected

2: no results (enhanced)

NOTE: Starting in v0.10.12, if you have the feature ‘useEnhancedExitCodes’ turned on, then choco will provide enhanced exit codes that allow better integration and scripting.

The syntax for returns is:

returns [0, 2, 1605, 1614, 1641]

Updated in Chef Infra Client 15.3.

New in Chef Client 12.18

source
Ruby Type: String

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

timeout
Ruby Type: String, Integer

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

user
Ruby Type: String

The username to authenticate feeds.

New in Chef Infra Client 15.3

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chocolatey_package resource in recipes:

Install a Chocolatey package:

chocolatey_package 'name of package' do
  action :install
end

Install a package with options with Chocolatey’s --checksum option:

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

chocolatey_source resource

chocolatey_source resource page

Use the chocolatey_source resource to add, remove, enable, or disable Chocolatey sources.

New in Chef Infra Client 14.3.

Syntax


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

chocolatey_source 'name' do
  admin_only              true, false # default value: false
  allow_self_service      true, false # default value: false
  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 Chef Infra Client will take to bring the node into the desired state.
  • admin_only, allow_self_service, 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.
:disable
Disables a Chocolatey source. New in Chef Infra Client 15.1.
:enable
Enables a Chocolatey source. New in Chef Infra Client 15.1.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Removes a Chocolatey source.

Properties


The chocolatey_source resource has the following properties:

admin_only
Ruby Type: true, false | Default Value: false

Whether or not to set the source to be accessible to only admins.

New in Chef Infra Client 15.1

allow_self_service
Ruby Type: true, false | Default Value: false

Whether or not to set the source to be used for self service.

New in Chef Infra Client 15.1

bypass_proxy
Ruby Type: true, false | Default Value: false

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

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: The resource block's name

An optional property to set the source name if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the chocolatey_source resource in recipes:

Add a Chocolatey source

chocolatey_source 'MySource' do
  source 'http://example.com/something'
  action :add
end

Remove a Chocolatey source

chocolatey_source 'MySource' do
  action :remove
end

cookbook_file resource

cookbook_file resource page

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 Chef Infra 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 Infra 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 Infra Server. A file is not transferred when the checksums match. Only files that require an update are transferred from the Chef Infra 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                     Integer, false # default value: 5
  cookbook                   String
  force_unlink               true, false # default value: false
  group                      String, Integer
  inherits                   true, false
  manage_symlink_source      true, false
  mode                       String, Integer
  owner                      String, Integer
  path                       String # default value: 'name' unless specified
  rights                     Hash
  source                     String, Array
  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 Chef Infra 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
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra 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 | Default Value: False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.

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 | Default Value: The current cookbook name

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

force_unlink
Ruby Type: true, false | Default Value: false

How Chef Infra 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 Chef Infra Client delete the non-file target and replace it with the specified file. Set to false for Chef Infra Client to raise an error.

group
Ruby Type: Integer, String

A string or ID that identifies the group owner by group name or SID, 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).

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, Chef Infra 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, Chef Infra 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', Chef Infra 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.

owner
Ruby Type: Integer, String

A string or ID that identifies the group owner by user name or SID, 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. 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 Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended.

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: The resource block's 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.

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, Chef Infra 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

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 Infra 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, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra 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, Chef Infra 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; Chef Infra 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. The principal can be specified by either name or SID. When using 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. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the SDDL string constants. Chef Infra 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 TypeDescription
:applies_to_childrenSpecify 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_selfIndicates 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_deepIndicates 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, 'S-1-1-0'
  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, %w(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. Chef Infra 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, %w(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 Chef Infra 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, Chef Infra Client will default it to true, which will ensure that security settings for existing files remain unchanged.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

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-20.04
   ubuntu-20
   ubuntu
   redhat-8.2
   redhat-7.8
   ...
   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-20.04/apache2_module_conf_generate.pl
ubuntu-20/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 the cookbook_file resource in recipes:

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

cron resource page

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 'chefio'
  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              Integer, String # default value: "*"
  environment      Hash
  home             String
  hour             Integer, String # default value: "*"
  mailto           String
  minute           Integer, String # default value: "*"
  month            Integer, String # default value: "*"
  path             String
  shell            String
  time             Symbol
  time_out         Hash
  user             String # default value: "root"
  weekday          Integer, String, Symbol # default value: "*"
  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 Chef Infra Client will take to bring the node into the desired state.
  • command, day, environment, home, hour, mailto, minute, month, path, shell, time, time_out, 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
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


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

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'}). Note: These variables must exist for a command to be run successfully.

home
Ruby Type: String

Set the HOME environment variable.

hour
Ruby Type: Integer, String | Default Value: *

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

mailto
Ruby Type: String

Set the MAILTO environment variable.

minute
Ruby Type: Integer, String | Default Value: *

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

month
Ruby Type: Integer, String | Default Value: *

The month in the year on which a cron entry is to run (1 - 12, jan-dec, or *).

path
Ruby Type: String

Set the PATH environment variable.

shell
Ruby Type: String

Set the SHELL environment variable.

time
Ruby Type: Symbol
Allowed Values: :annually, :daily, :hourly, :midnight, :monthly, :reboot, :weekly, :yearly

A time interval.

time_out
Ruby Type: Hash

A Hash of timeouts in the form of ({'OPTION' => 'VALUE'}). Accepted valid options are:

  • preserve-status (BOOL, default: ‘false’),
  • foreground (BOOL, default: ‘false’),
  • kill-after (in seconds),
  • signal (a name like ‘HUP’ or a number)

New in Chef Infra Client 15.7

user
Ruby Type: String | Default Value: root

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. This property is not applicable on the AIX platform.

weekday
Ruby Type: Integer, String, Symbol | Default Value: *

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


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the cron resource 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 { ::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 '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_access resource

cron_access resource page

Use the cron_access resource to manage cron’s cron.allow and 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 Infra Client releases.

New in Chef Infra Client 14.4.

Syntax


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

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 Chef Infra 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
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The cron_access resource has the following properties:

user
Ruby Type: String | Default Value: The resource block's name

An optional property to set the user name if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the cron_access resource 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 jenkins user access to cron for security purposes' do
  user 'jenkins'
  action :deny
end

cron_d resource

cron_d resource page

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

Warning

Chef Infra Client also ships with 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 Infra 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
  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
  time_out              Hash
  user                  String # default value: "root"
  weekday               Integer, String, Symbol # 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 Chef Infra Client will take to bring the node into the desired state.
  • command, comment, cron_name, day, environment, home, hour, mailto, minute, mode, month, path, predefined_value, random_delay, shell, time_out, 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.
:create_if_missing
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.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra 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.

comment
Ruby Type: String

A comment to place in the cron.d file.

cron_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the cron name if it differs from the resource block’s 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'}). Note: These variables must exist for a command to be run successfully.

home
Ruby Type: String

Set the HOME environment variable.

hour
Ruby Type: Integer, String | Default Value: *

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

mailto
Ruby Type: String

Set the MAILTO environment variable.

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"

The octal mode of the generated crontab file.

month
Ruby Type: Integer, String | Default Value: *

The month in the year on which a cron entry is to run (1 - 12, jan-dec, or *).

path
Ruby Type: String

Set the PATH environment variable.

predefined_value
Ruby Type: String
Allowed Values: "@annually", "@daily", "@hourly", "@midnight", "@monthly", "@reboot", "@weekly", "@yearly"

Schedule your cron job with one of the special predefined value instead of ** * pattern.

random_delay
Ruby Type: Integer

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

shell
Ruby Type: String

Set the SHELL environment variable.

time_out
Ruby Type: Hash

A Hash of timeouts in the form of ({'OPTION' => 'VALUE'}). Accepted valid options are:

  • preserve-status (BOOL, default: ‘false’),
  • foreground (BOOL, default: ‘false’),
  • kill-after (in seconds),
  • signal (a name like ‘HUP’ or a number)

New in Chef Infra Client 15.7

user
Ruby Type: String | Default Value: root

The name of the user that runs the command.

weekday
Ruby Type: Integer, String, Symbol | Default Value: *

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


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the cron_d resource in recipes:

Run a program on the fifth hour of the day

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 an entry every Saturday, 8:00 AM

cron_d 'name_of_cron_entry' do
  minute '0'
  hour '8'
  weekday '6'
  mailto 'admin@example.com'
  command '/bin/true'
  action :create
end

Run an entry 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'
  command '/bin/true'
  action :create
end

Remove a cron job by name:

cron_d 'job_to_remove' do
  action :delete
end

csh resource

csh resource page

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.

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
  path                       Array
  returns                    Integer, Array
  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 Chef Infra 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

The current working directory from which the command will be 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.)

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.

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.

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.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


This resource does not have any examples.

directory resource

directory resource page

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
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  recursive                  true, false
  rights                     Hash
  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 Chef Infra 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
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The directory resource has the following properties:

group
Ruby Type: Integer, String

A string or ID that identifies the group owner by group name or SID, 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).

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, Chef Infra 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', Chef Infra 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.

owner
Ruby Type: Integer, String

A string or ID that identifies the group owner by user name or SID, 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: The resource block's 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 parent directories recursively and delete directories, subdirectories, and files recursively. The owner, group, and mode properties apply only to the leaf directory.

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.

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.

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; Chef Infra 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. The principal can be specified by either name or SID. When using 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. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the SDDL string constants. Chef Infra 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 TypeDescription
:applies_to_childrenSpecify 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_selfIndicates 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_deepIndicates 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, 'S-1-1-0'
  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, %w(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. Chef Infra 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, %w(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 Chef Infra 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, Chef Infra Client will default it to true, which will ensure that security settings for existing files remain unchanged.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the directory resource in recipes:

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" do
  rights :full_control, "DOMAIN\\User"
  inherits false
  action :create
end

or:

directory 'C:\tmp\something' 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).

  </div>
</div>

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

dmg_package resource page

Use the dmg_package resource to install a package from a .dmg file. The resource will retrieve the dmg file from a remote URL, mount it using macOS' hdidutil, copy the application (.app directory) 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 Infra Client 14.0.

Syntax


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

dmg_package 'name' do
  accept_eula          true, false # default value: false
  allow_untrusted      true, false # default value: false
  app                  String # default value: 'name' unless specified
  checksum             String
  destination          String # default value: "/Applications"
  dmg_name             String # default value: The value passed for the application name.
  dmg_passphrase       String
  file                 String
  headers              Hash
  owner                String, Integer
  package_id           String
  source               String
  type                 String # default value: "app"
  volumes_dir          String # default value: The value passed for the application name.
  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 Chef Infra Client will take to bring the node into the desired state.
  • accept_eula, allow_untrusted, app, checksum, destination, dmg_name, dmg_passphrase, file, headers, owner, package_id, source, 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
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The dmg_package resource has the following properties:

accept_eula
Ruby Type: true, false | Default Value: false

Specify whether to accept the EULA. Certain dmg files require acceptance of EULA before mounting.

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: The resource block's name

The name of the application as it appears in the /Volumes directory if it differs from the resource block’s 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 | Default Value: The value passed for the application name.

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 absolute path to the .dmg file on the local system.

headers
Ruby Type: Hash

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

owner
Ruby Type: String, Integer

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

type
Ruby Type: String | Default Value: app
Allowed Values: "app", "mpkg", "pkg"

The type of package.

volumes_dir
Ruby Type: String | Default Value: The value passed for the application name.

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


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Examples


The following examples demonstrate various approaches for using the dmg_package resource in recipes:

Install Google Chrome via the DMG package:

dmg_package 'Google Chrome' do
  dmg_name 'googlechrome'
  source   'https://dl-ssl.google.com/chrome/mac/stable/GGRM/googlechrome.dmg'
  checksum '7daa2dc5c46d9bfb14f1d7ff4b33884325e5e63e694810adc58f14795165c91a'
  action   :install
end

Install Virtualbox from the .mpkg:

dmg_package 'Virtualbox' do
  source 'http://dlc.sun.com.edgesuite.net/virtualbox/4.0.8/VirtualBox-4.0.8-71778-OSX.dmg'
  type   'mpkg'
end

Install pgAdmin and automatically accept the EULA:

dmg_package 'pgAdmin3' do
  source   'http://wwwmaster.postgresql.org/redir/198/h/pgadmin3/release/v1.12.3/osx/pgadmin3-1.12.3.dmg'
  checksum '9435f79d5b52d0febeddfad392adf82db9df159196f496c1ab139a6957242ce9'
  accept_eula true
end

dnf_package resource

dnf_package resource page

Use the dnf_package resource to install, upgrade, and remove packages with DNF for Fedora and RHEL 8+. 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.

New in Chef Infra Client 12.18.

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       Hash # default value: {"before"=>false, "after"=>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:

  • dnf_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • arch, flush_cache, options, package_name, source, timeout, and version are the properties available to 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
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra 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: Hash | Default Value: {"before"=>false, "after"=>false}

Flush the in-memory cache before or after a DNF operation that installs, upgrades, or removes a package.

DNF automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while a Chef Infra 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.

options
Ruby Type: String, Array

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

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String

The optional path to a package on the local file system.

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 Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying 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 a Chef Infra 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.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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 Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra 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.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying 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 a Chef Infra 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 the dnf_package resource in recipes:

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

dpkg_package resource page

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.

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
  options                      String, Array
  package_name                 String, Array
  response_file                String
  response_file_variables      Hash
  source                       String, Array
  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 Chef Infra 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 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
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra 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:

options
Ruby Type: String, Array

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

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

response_file
Ruby Type: String

The direct path to the file used to pre-seed a package.

response_file_variables
Ruby Type: Hash

A Hash of response file variables in the form of {‘VARIABLE’ => ‘VALUE’}.

source
Ruby Type: String, Array

The path to a package in the local file system.

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.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts 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 Chef InfraClient.

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 a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

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

Ruby Type: Symbol, 'Chef::Resource[String]'

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing 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 a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

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

Guards

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

  • 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