Skip to main content

All Infra Resources

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 and retry_delay common properties

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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 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 using 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 for each resource 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 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, :full_control, or an integer.

Integers used for permissions must match the following list FileSystemRights Enum fields.

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

:applies_to_children

Specify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).

:applies_to_self

Indicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.

:one_level_deep

Indicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, '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. Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of 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 Infra Client:

alternatives resource

alternatives resource page

Use the alternatives resource to configure 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
Set an alternative up in automatic mode with the highest priority automatically selected.
:install
Install an alternative on the system including symlinks. (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.
:refresh
Refresh alternatives.
:remove
Remove an alternative and all associated links.
:set
Set the symlink for an alternative.

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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, Ubuntu, and other platforms that use the APT package system.

Note

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

Syntax

An 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
  anchor_package_regex       true, false # default value: false
  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 # default value: {}
  source                     String
  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.
  • anchor_package_regex, default_release, options, overwrite_config_files, package_name, response_file, response_file_variables, source, timeout, and version are the properties available to this resource.

Actions

The apt_package resource has the following actions:

:install
Install a package. If a version is specified, install the specified version of the package. (default)
: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
Change the installed package.
:remove
Remove a package.
:unlock
Unlocks the apt package so that it can be upgraded to a newer version.
:upgrade
Install a package and ensure that a package is the latest version.

Properties

The apt_package resource has the following properties:

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

A Boolean flag that allows (false) or prevents (true) apt_package from matching the named package with packages by regular expression if it can’t find a package with the exact same name.

New in Chef Infra Client 18.3

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 | Default Value: {}

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.

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 using 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, using 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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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 using 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, using 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 %w(package1 package2 package3)

Install without using recommend packages as a dependency:

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

Prevent the apt_package resource from installing packages with pattern matching names:

By default, the apt_package resource will install the named package. If it can’t find a package with the exact same name, it will treat the package name as regular expression string and match with any package that matches that regular expression. This may lead Chef Infra Client to install one or more packages with names that match that regular expression.

In this example, anchor_package_regex true prevents the apt_package resource from installing matching packages if it can’t find the lua5.3 package.

apt_package 'lua5.3' do
  version '5.3.3-1.1ubuntu2'
  anchor_package_regex true
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
Creates a preferences file under /etc/apt/preferences.d. (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.
: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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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 # default value: []
  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
  options            String, Array # default value: []
  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
Creates a repository file at /etc/apt/sources.list.d/ and builds the repository listing. (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.
: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 | Default Value: []

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.

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

Additional options to set for the repository.

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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

Add repository that needs custom options:

apt_repository 'corretto' do
  uri          'https://apt.corretto.aws'
  arch         'amd64'
  distribution 'stable'
  components   ['main']
  options      ['target-=Contents-deb']
  key          'https://apt.corretto.aws/corretto.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. (default)
: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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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
  strip_components      Integer # default value: 0
  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, path, and strip_components are the properties available to this resource.

Actions

The archive_file resource has the following actions:

:extract
Extract and archive file. (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 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.

strip_components
Ruby Type: Integer | Default Value: 0

Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. This behaves similarly to tar’s –strip-components command line argument.

New in Chef Infra Client 17.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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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

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

bash 'name' do
  code             String
  command          String, Array # default value: 'name' unless specified
  creates          String
  cwd              String
  default_env      true, false # default value: false
  domain           String
  elevated         true, false # default value: false
  environment      Hash
  flags            String
  group            String, Integer
  input            String
  interpreter      String
  live_stream      true, false # default value: false
  login            true, false # default value: false
  password         String
  returns          Integer, Array # default value: 0
  timeout          Integer, String, Float # default value: 3600
  user             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, command, creates, cwd, default_env, domain, elevated, environment, flags, group, input, interpreter, live_stream, login, password, returns, timeout, and user are the properties available to 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
Run a command. (default)

Properties

The bash resource has the following properties:

code
Ruby Type: String | REQUIRED

A quoted string of code to be executed.

command
Ruby Type: String, Array | Default Value: The resource block's name

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

Note

Use the execute resource to run a single command. Use multiple execute resource blocks to run multiple commands.

creates
Ruby Type: String

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

cwd
Ruby Type: String

The current working directory from which the command will be run.

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

When true this enables ENV magic to add path_sanity to the PATH and force the locale to English+UTF-8 for parsing output.

New in Chef Client 14.2

domain
Ruby Type: String

Windows only: The domain of the user specified by the user property. If not specified, the username 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.

New in Chef Client 12.21

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

Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) from interactively blocking the process. This will cause the process to be run under a batch login instead of an interactive login. The user running chef-client needs the ‘Replace a process level token’ and ‘Adjust Memory Quotas for a process’ permissions. The user that is running the command needs the ‘Log on as a batch job’ permission. Because this requires a login, the user and password properties are required.

New in Chef Client 13.3

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({'ENV_VARIABLE' => 'VALUE'}). Note: 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.

input
Ruby Type: String

An optional property to set the input sent to the command as STDIN.

New in Chef Infra Client 16.2

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

Send the output of the command run by this execute resource block to the Chef Infra Client event stream.

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

Use a login shell to run the commands instead of inheriting the existing execution environment.

New in Chef Infra Client 17.0

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.

New in Chef Client 12.21

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 of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. domain\user or user@my.dns.domain.com via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain property. On Windows only, if this property is specified, the password property must be 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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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:

Compile an application

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

Using escape characters in a string of code

In the following example, the find command uses an escape character (\). Use a second escape character (\\) to preserve the escape character in the code string:

bash 'delete some archives ' do
  code <<-EOH
    find ./ -name "*.tar.Z" -mtime +180 -exec rm -f {} \\;
  EOH
  ignore_failure true
end

Install a file from a remote location

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

git "#{Chef::Config[:file_cache_path]}/ruby-build" do
  repository 'git://github.com/rbenv/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

Using Attributes in Bash Code

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

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

batch 'name' do
  code             String
  command          String, Array # default value: 'name' unless specified
  creates          String
  cwd              String
  default_env      true, false # default value: false
  domain           String
  elevated         true, false # default value: false
  environment      Hash
  flags            String
  group            String, Integer
  input            String
  interpreter      String
  live_stream      true, false # default value: false
  login            true, false # default value: false
  password         String
  returns          Integer, Array # default value: 0
  timeout          Integer, String, Float # default value: 3600
  user             String, Integer
  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.
  • code, command, creates, cwd, default_env, domain, elevated, environment, flags, group, input, interpreter, live_stream, login, password, returns, timeout, and user are the properties available to 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 | Default Value: The resource block's name.

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, String, 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@subdomain.dns.example.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 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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

Note

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

Syntax

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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
Add a breakpoint for use with chef-shell (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

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 will not 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 > default[: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
Install build essential packages. (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.
: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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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
Install a cabinet package. If a version is specified, install the specified version of the package. (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.
:remove
Remove a 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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

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

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.

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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"
}

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.

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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
  data_collector_server_url      String
  data_collector_token           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
  policy_persist_run_list        true, false
  report_handlers                Array # default value: []
  rubygems_url                   String, Array
  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, data_collector_server_url, data_collector_token, 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, policy_persist_run_list, report_handlers, rubygems_url, 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
Create a client.rb config file and folders for configuring Chef Infra Client. (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.
:remove
Remove a client.rb config file for configuring Chef Infra Client.

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.

data_collector_server_url
Ruby Type: String

The data collector URL (typically automate) to send node, converge, and compliance data.

Note

If possible, use Chef Infra Server to do all data collection reporting, as this removes the need to distribute tokens to individual nodes.

New in Chef Infra Client 17.8

data_collector_token
Ruby Type: String

The data collector token to interact with the data collector server URL (Automate).

Note

If possible, use Chef Infra Server to do all data collection reporting, as this removes the need to distribute tokens to individual nodes.

New in Chef Infra Client 17.8

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: []

Client logging formatters to load.

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.

policy_persist_run_list
Ruby Type: true, false

Override run lists defined in a Policyfile with the run_list defined on the Chef Infra Server.

New in Chef Infra Client 17.3

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"')}]

rubygems_url
Ruby Type: String, Array

The location to source rubygems. It can be set to a string or array of strings for URIs to set as rubygems sources. This allows individuals to set up an internal mirror of rubygems for airgapped environments.

New in Chef Infra Client 17.11

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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 Chef Infra Server is the URL of the Chef 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

Report directly to the Chef Automate data collector endpoint.

chef_client_config 'Create client.rb' do
  chef_server_url 'https://chef.example.dmz'
  data_collector_server_url 'https://automate.example.dmz'
  data_collector_token 'TEST_TOKEN_TEST'
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 # default value: []
  day                      Integer, String # default value: "*"
  environment              Hash # default value: {}
  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. (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.
: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 | Default Value: []

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 | Default Value: {}

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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 on macOS systems.

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 # default value: []
  environment              Hash # default value: {}
  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. (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_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 | Default Value: []

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

environment
Ruby Type: Hash | Default Value: {}

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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 # default value: []
  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
  priority                  Integer # default value: 7
  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"
  use_consistent_splay      true, false # default value: false
  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, priority, run_on_battery, splay, start_date, start_time, task_name, use_consistent_splay, 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. (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.
: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: []

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.

priority
Ruby Type: Integer | Default Value: 7

Use to set Priority Levels range from 0 to 10.

New in Chef Infra Client 17.5

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.

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

Always use the same random splay amount for each node to ensure consistent frequencies between chef-client execution.

New in Chef Infra Client 17.5

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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

Run Chef Infra Client with a persistent delay on every run calculated once, similar to how chef_client_cron resource works:

chef_client_scheduled_task 'Run chef-client with persistent splay' do
  use_consistent_splay true
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 # default value: []
  delay_after_boot         String # default value: "1min"
  description              String # default value: "Chef Infra Client periodic execution"
  environment              Hash # default value: {}
  interval                 String # default value: "30min"
  job_name                 String # default value: "chef-client"
  run_on_battery           true, false # default value: true
  service_umask            Integer, String
  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, service_umask, 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. (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.
: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 | Default Value: []

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 | Default Value: {}

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.

service_umask
Ruby Type: Integer, String

Fix umask for hardened systems that have a changed default umask. This changes the chef-client umask so any files or folders are created with new umask. Recommend setting to stand install default of 0022.

New in Chef Infra Client 18.5

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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 a trusted certificate to Chef Infra Client’s trusted certificate directory (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.
:remove
Remove a trusted certificate from Chef Infra Client’s trusted certificate directory

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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, 2, and 3. When all of the machines in an organization are running chef-client version 13.0.113 (or higher), it is recommended that this value be set to 3.

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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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"
}

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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":{}
}

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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 Infra 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
Install a gem. If a version is specified, install the specified version of the gem. (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.
: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 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 unless `clear_gem_sources` set to true in the `client.rb` config.

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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:

exception

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

report

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

start

A 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 before 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 # default value: []
  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
Disables the handler for the current Chef Infra Client run on the current node.
:enable
Enables the handler for the current Chef Infra Client run on the current node. (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_handler resource has the following properties:

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

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

arguments :key1 => ''val1''

or:

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

class_name
Ruby Type: String | 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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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_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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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": {}
}

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.

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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": {}
}

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.

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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. (default)

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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

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.

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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, Mash (Hash-like) # 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
Creates the item, or updates it if it already exists. (default)
:create_if_missing
Calls the create action unless it exists.
:delete
Deletes the item and the item’s keys (‘id’_keys).
: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, Mash (Hash-like) | 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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.

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 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
Sets a Chocolatey config value. (default)
: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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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:\temp\choco'
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.

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 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
Disables a named Chocolatey feature.
:enable
Enables a named Chocolatey feature. (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 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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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_installer resource

chocolatey_installer resource page

Use the chocolatey_installer resource to install the Chocolatey package manager. Use the chocolatey_feature resource to customize your install and the chocolatey_package resource to install packages.

New in Chef Infra Client 18.4.

Syntax

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

chocolatey_installer 'name' do
  chocolatey_version      String
  download_url            String
  ignore_proxy            true, false # default value: false
  proxy_password          String
  proxy_url               String
  proxy_user              String
  use_native_unzip        true, false # default value: false
  action                  Symbol # defaults to :install if not specified
end

where:

  • chocolatey_installer 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.
  • chocolatey_version, download_url, ignore_proxy, proxy_password, proxy_url, proxy_user, and use_native_unzip are the properties available to this resource.

Actions

The chocolatey_installer resource has the following actions:

:install
Installs Chocolatey package manager (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.
:uninstall
Uninstall Chocolatey package manager.
:upgrade
Upgrades the Chocolatey package manager.

Properties

The chocolatey_installer resource has the following properties:

chocolatey_version
Ruby Type: String

Specifies a target version of Chocolatey to install. By default, the latest stable version is installed. This will use the value in $env:ChocolateyVersion by default if that environment variable is present. This parameter is ignored if you set download_url.

download_url
Ruby Type: String

The URL to download Chocolatey from. This sets the value of $env:ChocolateyDownloadUrl and causes the installer to choose an alternate download location. If this is not set, this resource downloads Chocolatey from the official Chocolatey community repository. You can set a path to a chocolatey.nupkg file for offline installation.

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

If set, this overrides any configured proxy, proxy environment variables, or parameters. This is enabled if set to a value other than ‘false’ or ‘0’.

proxy_password
Ruby Type: String

The password used to connect to the proxy server with. If set, you must also set proxy_user.

proxy_url
Ruby Type: String

Specifies the proxy URL to use during the download.

proxy_user
Ruby Type: String

The username used to connect to the proxy server with. If set, you must also set proxy_password.

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

If true, this resource uses built-in Windows decompression tools instead of 7zip when unpacking the downloaded NuPkg file. This parameter is ignored in PowerShell 5+ in favour of using the Expand-Archive built-in PowerShell cmdlet directly.

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 delay in seconds between retry attempts.

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

Notifications

notifies

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

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

If the referenced resource does not exist, an error is raised. In contrast, subscribes will not fail if the source resource is not found.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each resource notified.

The syntax for notifies is:

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

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

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

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

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

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

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

If the other resource does not exist, the subscription will not raise an error. Contrast this with the stricter semantics of notifies, which will raise an error if the other resource does not exist.

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

:before

Specifies that the action on a notified resource should be run before processing the resource 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, for each 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.