Skip to main content

Resources Reference

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

Common Functionality

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

Actions

The following actions may be used with any resource:

:nothing

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

Examples

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

Use the :nothing action
service 'memcached' do
  action :nothing
end

Properties

The following properties are common to every resource:

ignore_failure

Ruby Type: true, false | Default Value: false

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

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

Examples

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

Use the ignore_failure common property
gem_package 'syntax' do
  action :install
  ignore_failure true
end
Use the retries common property
service 'apache' do
  action [ :enable, :start ]
  retries 3
end

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Arguments

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

:user

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

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

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

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

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

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

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

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

Set a timeout for a command. For example:

not_if 'sleep 10000', :timeout => 10

not_if Examples

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

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

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

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

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

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

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

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

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

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

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

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

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

only_if Examples

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

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

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

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

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

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

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  only_if { ! ::File.exist?('/etc/passwd') }
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:

attribute_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 attributes
  path '/foo/bar'
end

and a resource block that is doing lazy evaluation:

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

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

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

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

Notifications

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

Timers

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

Notifies

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

The syntax for notifies is:

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

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

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

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

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

and then Chef Infra Client would immediately run the following:

execute 'test-nagios-config' do
  command 'nagios3 --verify-config'
  action :nothing
end
Notify multiple resources
template '/etc/chef/server.rb' do
  source 'server.rb.erb'
  owner 'root'
  group 'root'
  mode '0755'
  notifies :restart, 'service[chef-solr]', :delayed
  notifies :restart, 'service[chef-solr-indexer]', :delayed
  notifies :restart, 'service[chef-server]', :delayed
end
Notify in a specific order

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

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

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

package 'bar'

execute 'restart_baz'

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

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

Reload a service
template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  notifies :reload, 'service[apache]', :immediately
end
Restart a service when a template is modified
template '/etc/www/configures-apache.conf' do
  notifies :restart, 'service[apache]', :immediately
end
Send notifications to multiple resources

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

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

service 'afpd'
service 'cnid'
Execute a command using a template

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

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

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

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

Restart a service, and then notify a different service

The following example shows how start a service named example_service and immediately notify the Nginx service to restart.

service 'example_service' do
  action :start
  notifies :restart, 'service[nginx]', :immediately
end
Restart one service before restarting another

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

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

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

Notify when a remote source changes
remote_file '/tmp/couch.png' do
  source 'http://couchdb.apache.org/img/sketch.png'
  action :nothing
end

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

Subscribes

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

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

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

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

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

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer
Examples
The following examples show how to use the subscribes notification in a recipe. Prevent restart and reconfigure if configuration is broken

Use the :nothing action (common to all resources) to prevent the test from starting automatically, and then use the subscribes notification to run a configuration test when a change to the template is detected:

execute 'test-nagios-config' do
  command 'nagios3 --verify-config'
  action :nothing
  subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately
end
Reload a service using a template

To reload a service that is based on a template, use the template and service resources together in the same recipe, similar to the following:

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

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

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

Stash a file in a data bag

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

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

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

Relative Paths

The following relative paths can be used with any resource:

#{ENV['HOME']}

Use to return the ~ path in Linux and macOS or the %HOMEPATH% in Microsoft Windows.

Examples

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

Run in Compile Phase

Chef Infra Client processes recipes in two phases:

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

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

Note

Use the chef_gem resource to install gems that are needed by Chef Infra Client during the execution phase.

run_action

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

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

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

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

build_essential 'Install compilers' do
  compile_time true
end

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

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

Using Custom Resources preferred to forcing to compile time

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

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

build_essential 'Install compilers' do
  compile_time true
end

chef_gem 'aws-dsk' do
  compile_time true
end

require 'aws-sdk'

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

unified_mode true

action :run do
  build_essential 'Install compilers'

  chef_gem 'aws-sdk'

  require 'aws-sdk'
end

Download and parse a configuration file

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

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

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

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

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

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

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

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

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

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

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

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

Notifications will not work

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

execute 'ifconfig'

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

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

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

Resources that are forced to compile time by default

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

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

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

Atomic File Updates

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

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

Note

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

Windows File Security

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

Access Control Lists (ACLs)

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

rights permission, principal, option_type => value

where

permission

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

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

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

principal

Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the SDDL string constants. Chef Infra Client does not need to know if a principal is a user or a group.

option_type

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

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

For example:

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

or:

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

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

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

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

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

or:

deny_rights :full_control, ['Sally']

Inheritance

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

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

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

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

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

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

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

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

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

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

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

Resources


The following resources are built into the Chef Client:

alternatives resource

alternatives resource page

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

New in Chef Infra Client 16.0.

Syntax


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

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

where:

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

Actions


The alternatives resource has the following actions:

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

Properties


The alternatives resource has the following properties:

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

The path to the alternatives link.

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

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

path
Ruby Type: String

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

priority
Ruby Type: String, Integer

The priority of the alternative.


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Install an alternative:

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

Set an alternative:

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

Set the automatic alternative state:

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

Refresh an alternative:

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

Remove an alternative:

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

apt_package resource

apt_package resource page

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

Syntax


A apt_package resource block manages a package on a node, typically by installing it. The simplest use of the apt_package resource is: apt_package 'package_name' which will install the named package using all of the default options and the default action of :install.

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

apt_package 'name' do
  default_release              String
  options                      String, Array
  overwrite_config_files       true, false # default value: false
  package_name                 String, Array
  response_file                String
  response_file_variables      Hash
  timeout                      String, Integer
  version                      String, Array
  action                       Symbol # defaults to :install if not specified
end

where:

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

Actions


The apt_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:lock
Locks the apt package to a specific version.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:reconfig
Reconfigure a package. This action requires a response file.
:remove
Remove a package.
:unlock
Unlocks the apt package so that it can be upgraded to a newer version.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The apt_package resource has the following properties:

default_release
Ruby Type: String

The default release. For example: stable.

options
Ruby Type: String, Array

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

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

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

New in Chef Client 14.0

package_name
Ruby Type: String, Array

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

response_file
Ruby Type: String

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

response_file_variables
Ruby Type: Hash

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

timeout
Ruby Type: String, Integer

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

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Multiple Packages

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

  • Download the specified packages and versions via a single HTTP transaction
  • Update or install multiple packages with a single resource during a Chef Infra Client run

For example, installing multiple packages:

package %w(package1 package2)

Installing multiple packages with versions:

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

Upgrading multiple packages:

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

Removing multiple packages:

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

Purging multiple packages:

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

Notifications, via an implicit name:

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

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

Note

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

Examples


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

Install a package using package manager:

apt_package 'name of package' do
  action :install
end

Install a package without specifying the default action:

apt_package 'name of package'

Install multiple packages at once:

apt_package %(package1 package2 package3)

Install without using recommend packages as a dependency:

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

apt_preference resource

apt_preference resource page

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

New in Chef Infra Client 13.3.

Syntax


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

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

where:

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

Actions


The apt_preference resource has the following actions:

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

Properties


The apt_preference resource has the following properties:

glob
Ruby Type: String

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

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

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

pin
Ruby Type: String | REQUIRED

The package version or repository to pin.

pin_priority
Ruby Type: String, Integer | REQUIRED

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


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Pin libmysqlclient16 to a version 5.1.49-3:

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

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

Unpin a libmysqlclient16:

apt_preference 'libmysqlclient16' do
  action :remove
end

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

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

apt_repository resource

apt_repository resource page

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

New in Chef Infra Client 12.9.

Syntax


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

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

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

apt_repository 'name' do
  arch               String, false
  cache_rebuild      true, false # default value: true
  components         Array # default value: `main` if using a PPA repository.
  cookbook           String, false
  deb_src            true, false # default value: false
  distribution       String, false # default value: The LSB codename of the node such as 'focal'.
  key                String, Array, false
  key_proxy          String, false
  keyserver          String, false # default value: "keyserver.ubuntu.com"
  repo_name          String # default value: 'name' unless specified
  trusted            true, false # default value: false
  uri                String
  action             Symbol # defaults to :add if not specified
end

where:

  • apt_repository is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • arch, cache_rebuild, components, cookbook, deb_src, distribution, key, key_proxy, keyserver, repo_name, trusted, and uri are the properties available to this resource.

Actions


The apt_repository resource has the following actions:

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

Properties


The apt_repository resource has the following properties:

arch
Ruby Type: String, false

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

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

Determines whether to rebuild the APT package cache.

components
Ruby Type: Array | Default Value: `main` if using a PPA repository.

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

cookbook
Ruby Type: String, false

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

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

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

distribution
Ruby Type: String, false | Default Value: The LSB codename of the node such as 'focal'.

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

key
Ruby Type: String, Array, false

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

key_proxy
Ruby Type: String, false

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

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

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

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

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

New in Chef Client 14.1

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

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

uri
Ruby Type: String

The base of the Debian distribution.


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Add repository with basic settings:

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

Enable Ubuntu multiverse repositories:

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

Add the Nginx PPA, autodetect the key and repository url:

apt_repository 'nginx-php' do
  uri          'ppa:nginx/stable'
end

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

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

Add repository that requires multiple keys to authenticate packages:

apt_repository 'rundeck' do
  uri 'https://dl.bintray.com/rundeck/rundeck-deb'
  distribution '/'
  key ['379CE192D401AB61', 'http://rundeck.org/keys/BUILD-GPG-KEY-Rundeck.org.key']
  keyserver 'keyserver.ubuntu.com'
  action :add
end

Add the Cloudera Repo of CDH4 packages for Ubuntu 16.04 on AMD64:

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

Remove a repository from the list:

apt_repository 'zenoss' do
  action :remove
end

apt_update resource

apt_update resource page

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

New in Chef Infra Client 12.7.

Syntax


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

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

where:

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

Nameless

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

apt_update

will behave the same as:

apt_update 'update'

Actions


The apt_update resource has the following actions:

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

Properties


The apt_update resource has the following properties:

frequency
Ruby Type: Integer | Default Value: 86400

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


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Update the Apt repository at a specified interval:

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

Update the Apt repository at the start of a Chef Infra Client run:

apt_update 'update'

archive_file resource

archive_file resource page

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

New in Chef Infra Client 15.0.

Syntax


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

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

where:

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

Actions


The archive_file resource has the following actions:

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

Properties


The archive_file resource has the following properties:

destination
Ruby Type: String | REQUIRED

The file path to extract the archive file to.

group
Ruby Type: String

The group of the extracted files.

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

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

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

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

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

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

owner
Ruby Type: String

The owner of the extracted files.

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

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


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Extract a zip file to a specified directory:

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

Set specific permissions on the extracted files:

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

bash resource

bash resource page

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

Syntax


A bash resource block executes scripts using Bash:

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

where:

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

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

bash 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  path                       Array
  returns                    Integer, Array
  timeout                    Integer, Float
  user                       String, Integer
  umask                      String, Integer
  action                     Symbol # defaults to :run if not specified
end

where:

  • bash is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • code, creates, cwd, environment, flags, group, path, returns, timeout, user, and umask are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The bash resource has the following actions:

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

Properties


The bash resource has the following properties:

code
Ruby Type: String | REQUIRED

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

creates
Ruby Type: String

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

cwd
Ruby Type: String

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

environment
Ruby Type: Hash

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

flags
Ruby Type: String

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

group
Ruby Type: String, Integer

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

returns
Ruby Type: Integer, Array | Default Value: 0

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

timeout
Ruby Type: Integer, String, Float | Default Value: 3600

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

user
Ruby Type: String, Integer

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

umask
Ruby Type: String, Integer

The file mode creation mask, or umask.


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Use a named provider to run a script

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

Install a file from a remote location using bash

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

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

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

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

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

Install an application from git using bash

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

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

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

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

Store certain settings

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

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

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

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

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

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

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

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

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

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

batch resource

batch resource page

Use the batch resource to execute a batch script using the cmd.exe interpreter on Windows. The batch resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Syntax


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

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

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

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

where:

  • batch is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • architecture, code, command, creates, cwd, flags, group, guard_interpreter, interpreter, returns, timeout, user, password and domain are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The batch resource has the following actions:

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

Properties


The batch resource has the following properties:

architecture
Ruby Type: Symbol

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

code
Ruby Type: String | REQUIRED

A quoted string of code to be executed.

command
Ruby Type: String, Array

The name of the command to be executed.

creates
Ruby Type: String

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

cwd
Ruby Type: String

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

flags
Ruby Type: String

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

group
Ruby Type: String, Integer

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

guard_interpreter
Ruby Type: Symbol | Default Value: :batch

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

interpreter
Ruby Type: String

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

returns
Ruby Type: Integer, Array | Default Value: 0

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

timeout
Ruby Type: Integer, Float | Default Value: 3600

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

user
Ruby Type: String

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

password
Ruby Type: String

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

domain
Ruby Type: String

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


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Unzip a file, and then move it

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

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

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

or:

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

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

Run a command as an alternate user

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

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

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

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

The following example shows how to run mkdir test_dir from a Chef Infra Client run as an alternate user.

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

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

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

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

bff_package resource

bff_package resource page

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

Note

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

Syntax


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

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

where:

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

Actions


The bff_package resource has the following actions:

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

Properties


The bff_package resource has the following properties:

options
Ruby Type: String, Array

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

package_name
Ruby Type: String

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

source
Ruby Type: String

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

timeout
Ruby Type: String, Integer

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

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Install a package

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

Using the base package resource:

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

Using the bff_package resource:

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

breakpoint resource

breakpoint resource page

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

New in Chef Infra Client 12.0.

Syntax


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

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

where:

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

Actions


The breakpoint resource has the following actions:

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

Properties


This resource does not have any properties.

Debug Recipes with chef-shell

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

Modes

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

ModeDescription
StandaloneDefault. No cookbooks are loaded, and the run-list is empty.
Solochef-shell acts as a Chef Solo Client. It attempts to load the chef-solo configuration file at ~/.chef/config.rb and any JSON attributes passed. If the JSON attributes set a run-list, it will be honored. Cookbooks will be loaded in the same way that chef-solo loads them. chef-solo mode is activated with the -s or --solo command line option, and JSON attributes are specified in the same way as for chef-solo, with -j /path/to/chef-solo.json.
Clientchef-shell acts as a Chef Infra Client. During startup, it reads the Chef Infra Client configuration file from ~/.chef/client.rb and contacts the Chef Infra Server to get the node's run_list, attributes, and cookbooks. Chef Infra Client mode is activated with the -z or --client options. You can also specify the configuration file with -c CONFIG and the server URL with -S SERVER_URL.

Configure

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

  1. If a configuration file is specified using the -c option, chef-shell will use the specified configuration file
  2. If a NAMED_CONF is given, chef-shell will load ~/.chef/NAMED_CONF/chef_shell.rb
  3. If no NAMED_CONF is given chef-shell will load ~/.chef/chef_shell.rb if it exists
  4. If no chef_shell.rb can be found, chef-shell falls back to load:
    • /etc/chef/client.rb if -z option is given.
    • /etc/chef/solo.rb if –solo-legacy-mode option is given.
    • .chef/config.rb if -s option is given.
    • .chef/knife.rb if -s option is given.

chef-shell.rb

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

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

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

Run as a Chef Infra Client

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

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

chef-shell -z

Manage

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

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

chef-shell -z named_configuration

Where:

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

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

chef (preprod) > items.command

Where:

  • items is the type of item to search for: cookbooks, clients, nodes, roles, environments or a data bag.
  • command is the command: list, show, find, or edit.

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

chef (preprod) > nodes.list

Which will return something similar to:

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

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

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

will return something similar to:

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

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

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

will return something similar to:

=> node[i-f09a939b]

Or:

chef (preprod) > load_balancer.ec2.public_hostname

will return something similar to:

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

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

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

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

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

will return something similar to:

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

Or:

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

will return something similar to:

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

Use Breakpoints

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

Step Through Run-list

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

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

and then run Chef Infra Client:

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

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

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

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

after-breakpoint
before-breakpoint

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

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

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

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

Rewind, and then resume your Chef Infra Client run to get the expected results:

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

Debug Existing Recipe

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

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

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

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

chef (15.8.23)>

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

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

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

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

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

Advanced Debugging

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

chef > tracing on
tracing is on
=> nil
chef >

and:

chef > tracing off
#0:(irb):2:Object:-: tracing off
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:109:Shell::Extensions::ObjectCoreExtensions:>:       def off
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:110:Shell::Extensions::ObjectCoreExtensions:-:         :off
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:111:Shell::Extensions::ObjectCoreExtensions:<:       end
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:272:main:>:       def tracing(on_or_off)
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:273:main:-:         conf.use_tracer = on_or_off.on_off_to_bool
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:162:Shell::Extensions::Symbol:>:       def on_off_to_bool
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:163:Shell::Extensions::Symbol:-:         to_s.on_off_to_bool
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:149:Shell::Extensions::String:>:       def on_off_to_bool
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:150:Shell::Extensions::String:-:         case self
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:154:Shell::Extensions::String:-:           false
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:158:Shell::Extensions::String:<:       end
#0:/opt/chef-workstation/embedded/lib/ruby/gems/2.6.0/gems/chef-15.8.23/lib/chef/shell/ext.rb:164:Shell::Extensions::Symbol:<:       end
tracing is off
=> nil
chef >

Debug Examples

The following examples show how to use chef-shell.

"Hello World"

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

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

bin/chef-shell

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

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

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

  chef (15.8.23)>

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

chef > recipe_mode
  chef:recipe_mode >

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

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

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

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

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

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

Switch back to recipe_mode context and use the attributes:

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

Now, run Chef Infra Client again:

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

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

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

Get Specific Nodes

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

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

Note

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

Examples


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

A recipe without a breakpoint

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

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

The same recipe with breakpoints

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

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

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

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

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

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

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

build_essential resource

build_essential resource page

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

New in Chef Infra Client 14.0.

Syntax


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

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

where:

  • build_essential is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • raise_if_unsupported is the property available to this resource.

Nameless

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

build_essential

will behave the same as:

build_essential 'install tools'

Actions


The build_essential resource has the following actions:

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

Properties


The build_essential resource has the following properties:

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

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

New in Chef Infra Client 15.5


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Install compilation packages:

build_essential

Install compilation packages during the compilation phase:

build_essential 'Install compilation tools' do
  compile_time true
end

Upgrade compilation packages on macOS systems:

build_essential 'Install compilation tools' do
  action :upgrade
end

cab_package resource

cab_package resource page

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

New in Chef Infra Client 12.15.

Syntax


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

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

where:

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

Actions


The cab_package resource has the following actions:

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

Properties


The cab_package resource has the following properties:

options
Ruby Type: String, Array

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

package_name
Ruby Type: String

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

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

The local file path or URL for the CAB package.

timeout
Ruby Type: String, Integer

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

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

Using local path in source

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

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

Using URL in source

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

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

chef_acl resource

chef_acl resource page

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

Syntax


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

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

where:

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

Actions


The chef_acl resource has the following actions:

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

Properties


The chef_acl resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

path

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

raw_json

Chef Infra Client as JSON data. For example:

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

recursive

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

remove_rights

Use to remove rights. For example:

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

or:

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

or:

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

retries
Ruby Type: Integer | Default Value: 0

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

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

rights

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

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

or:

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

or:

rights :all, :users => 'jkeiser'

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Examples


This resource does not have any examples.

chef_client resource

chef_client resource page

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

Syntax


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

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

where:

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

Actions


The chef_client resource has the following actions:

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

Properties


The chef_client resource has the following properties:

admin

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

chef_server

The URL for the Chef Infra Server.

complete

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

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

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

name

The name of Chef Infra Client.

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

output_key_format

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

output_key_path

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

raw_json

Chef Infra Client as JSON data. For example:

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

retries
Ruby Type: Integer | Default Value: 0

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

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source_key

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

source_key_pass_phrase

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

source_key_path

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

validator

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

Examples


This resource does not have any examples.

chef_client_cron resource

chef_client_cron resource page

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

New in Chef Infra Client 16.0.

Syntax


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

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

where:

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

Actions


The chef_client_cron resource has the following actions:

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

Properties


The chef_client_cron resource has the following properties:

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

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

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

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

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

The path to the chef-client binary.

comment
Ruby Type: String

A comment to place in the cron.d file.

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

The path of the config directory.

daemon_options
Ruby Type: Array

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

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

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

environment
Ruby Type: Hash

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

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

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

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

The name of the cron job to create.

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

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

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

The name of the log file to use.

mailto
Ruby Type: String

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

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

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

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

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

nice
Ruby Type: Integer, String

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

New in Chef Infra Client 16.5

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

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

user
Ruby Type: String | Default Value: root

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

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

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


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


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

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

chef_client_cron "Run Chef Infra Client as a cron job"

Run Chef Infra Client twice a day:

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

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

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

chef_client_launchd resource

chef_client_launchd resource page

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

New in Chef Infra Client 16.5.

Syntax


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

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

where:

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

Actions


The chef_client_launchd resource has the following actions:

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

Properties


The chef_client_launchd resource has the following properties:

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

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

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

The path to the chef-client binary.

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

The path of the config directory.

daemon_options
Ruby Type: Array

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

environment
Ruby Type: Hash

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

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

Time in minutes between Chef Infra Client executions.

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

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

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

The name of the log file to use.

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

Run the chef-client process with low priority disk IO

nice
Ruby Type: Integer, String

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

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

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

user
Ruby Type: String | Default Value: root

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

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

The working directory to run the Chef Infra Client from.


Common Resource Functionality


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

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

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

ignore_failure

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

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

retries

Ruby Type: Integer | Default Value: 0

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

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for notifies is:

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

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

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

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

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

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

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

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

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

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

The syntax for subscribes is:

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

Guards

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

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chef_client_launchd resource in recipes:

Set the Chef Infra Client to run on a schedule:

chef_client_launchd 'Setup the Chef Infra Client to run every 30 minutes' do
  interval 30
  action :enable
end

Disable the Chef Infra Client running on a schedule:

chef_client_launchd 'Prevent the Chef Infra Client from running on a schedule' do
  action :disable
end

chef_client_scheduled_task resource

chef_client_scheduled_task resource page

Use the chef_client_scheduled_task resource to setup the Chef Infra Client to run as a Windows scheduled task. This resource will also create the specified log directory if it doesn’t already exist.

New in Chef Infra Client 16.0.

Syntax


The full syntax for all of the properties that are available to the chef_client_scheduled_task resource is:

chef_client_scheduled_task 'name' do
  accept_chef_license      true, false # default value: false
  chef_binary_path         String # default value: "C:/opscode/chef/bin/chef-client"
  config_directory         String # default value: "/etc/chef"
  daemon_options           Array
  frequency                String # default value: "minute"
  frequency_modifier       Integer, String # default value: "30 if frequency is 'minute', 1 otherwise"
  log_directory            String # default value: "CONFIG_DIRECTORY/log"
  log_file_name            String # default value: "client.log"
  password                 String
  run_on_battery           true, false # default value: true
  splay                    Integer, String # default value: 300
  start_date               String
  start_time               String
  task_name                String # default value: "chef-client"
  user                     String # default value: "System"
  action                   Symbol # defaults to :add if not specified
end

where:

  • chef_client_scheduled_task is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • accept_chef_license, chef_binary_path, config_directory, daemon_options, frequency, frequency_modifier, log_directory, log_file_name, password, run_on_battery, splay, start_date, start_time, task_name, and user are the properties available to this resource.

Actions


The chef_client_scheduled_task resource has the following actions:

:add
Add a Windows Scheduled Task that runs Chef Infra Client.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove a Windows Scheduled Task that runs Chef Infra Client.

Properties


The chef_client_scheduled_task resource has the following properties:

accept_chef_license
Ruby Type: true, false | Default Value: false

Accept the Chef Online Master License and Services Agreement. See https://www.chef.io/online-master-agreement/

chef_binary_path
Ruby Type: String | Default Value: C:/opscode/chef/bin/chef-client

The path to the chef-client binary.

config_directory
Ruby Type: String | Default Value: /etc/chef

The path of the config directory.

daemon_options
Ruby Type: Array | Default Value: lazy default

An array of options to pass to the chef-client command.

frequency
Ruby Type: String | Default Value: minute
Allowed Values: "daily", "hourly", "minute", "monthly", "on_idle", "on_logon", "once", "onstart"

Frequency with which to run the task.

frequency_modifier
Ruby Type: Integer, String | Default Value: 30 if frequency is 'minute', 1 otherwise

Numeric value to go with the scheduled task frequency

log_directory
Ruby Type: String | Default Value: CONFIG_DIRECTORY/log

The path of the directory to create the log file in.

log_file_name
Ruby Type: String | Default Value: client.log

The name of the log file to use.

password
Ruby Type: String

The password for the user that Chef Infra Client runs as.

run_on_battery
Ruby Type: true, false | Default Value: true

Run the Chef Infra Client task when the system is on batteries.

splay
Ruby Type: Integer, String | Default Value: 300

A random number of seconds between 0 and X to add to interval so that all chef-client commands don’t execute at the same time.

start_date
Ruby Type: String

The start date for the task in m:d:Y format (ex: 12/17/2020).

start_time
Ruby Type: String

The start time for the task in HH:mm format (ex: 14:00). If the frequency is minute default start time will be Time.now plus the frequency_modifier number of minutes.

task_name
Ruby Type: String | Default Value: chef-client

The name of the scheduled task to create.

user
Ruby Type: String | Default Value: System

The name of the user that Chef Infra Client runs as.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chef_client_scheduled_task resource in recipes:

Setup Chef Infra Client to run using the default 30 minute cadence:

  chef_client_scheduled_task "Run Chef Infra Client as a scheduled task"

Run Chef Infra Client on system start:

  chef_client_scheduled_task 'Chef Infra Client on start' do
    frequency 'onstart'
  end

Run Chef Infra Client with extra options passed to the client:

  chef_client_scheduled_task "Run an override recipe" do
    daemon_options ["--override-runlist mycorp_base::default"]
  end

Run Chef Infra Client daily at 01:00 am, specifying a named run-list:

  chef_client_scheduled_task "Run chef-client named run-list daily" do
    frequency 'daily'
    start_time '01:00'
    daemon_options ['-n audit_only']
  end

chef_client_systemd_timer resource

chef_client_systemd_timer resource page

Use the chef_client_systemd_timer resource to setup the Chef Infra Client to run as a systemd timer.

New in Chef Infra Client 16.0.

Syntax


The full syntax for all of the properties that are available to the chef_client_systemd_timer resource is:

chef_client_systemd_timer 'name' do
  accept_chef_license      true, false # default value: false
  chef_binary_path         String # default value: "/opt/chef/bin/chef-client"
  config_directory         String # default value: "/etc/chef"
  cpu_quota                Integer, String
  daemon_options           Array
  delay_after_boot         String # default value: "1min"
  description              String # default value: "Chef Infra Client periodic execution"
  environment              Hash
  interval                 String # default value: "30min"
  job_name                 String # default value: "chef-client"
  run_on_battery           true, false # default value: true
  splay                    String # default value: "5min"
  user                     String # default value: "root"
  action                   Symbol # defaults to :add if not specified
end

where:

  • chef_client_systemd_timer is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • accept_chef_license, chef_binary_path, config_directory, cpu_quota, daemon_options, delay_after_boot, description, environment, interval, job_name, run_on_battery, splay, and user are the properties available to this resource.

Actions


The chef_client_systemd_timer resource has the following actions:

:add
Add a systemd timer that runs Chef Infra Client.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove a systemd timer that runs Chef Infra Client.

Properties


The chef_client_systemd_timer resource has the following properties:

accept_chef_license
Ruby Type: true, false | Default Value: false

Accept the Chef Online Master License and Services Agreement. See https://www.chef.io/online-master-agreement/

chef_binary_path
Ruby Type: String | Default Value: /opt/chef/bin/chef-client

The path to the chef-client binary.

config_directory
Ruby Type: String | Default Value: /etc/chef

The path of the config directory.

cpu_quota
Ruby Type: Integer, String

The systemd CPUQuota to run the chef-client process with. This is a percentage value of the total CPU time available on the system. If the system has more than 1 core this may be a value greater than 100.

New in Chef Infra Client 16.5

daemon_options
Ruby Type: Array

An array of options to pass to the chef-client command.

delay_after_boot
Ruby Type: String | Default Value: 1min

The time to wait after booting before the interval starts. This is expressed as a systemd time span such as 300seconds, 1hr, or 1m. See https://www.freedesktop.org/software/systemd/man/systemd.time.html for a complete list of allowed time span values.

description
Ruby Type: String | Default Value: Chef Infra Client periodic execution

The description to add to the systemd timer. This will be displayed when running systemctl status for the timer.

environment
Ruby Type: Hash

A Hash containing additional arbitrary environment variables under which the systemd timer will be run in the form of ({'ENV_VARIABLE' => 'VALUE'}).

interval
Ruby Type: String | Default Value: 30min

The interval to wait between executions. This is expressed as a systemd time span such as 300seconds, 1hr, or 1m. See https://www.freedesktop.org/software/systemd/man/systemd.time.html for a complete list of allowed time span values.

job_name
Ruby Type: String | Default Value: chef-client

The name of the system timer to create.

run_on_battery
Ruby Type: true, false | Default Value: true

Run the timer for Chef Infra Client if the system is on battery.

splay
Ruby Type: String | Default Value: 5min

A interval between 0 and X to add to the interval so that all chef-client commands don’t execute at the same time. This is expressed as a systemd time span such as 300seconds, 1hr, or 1m. See https://www.freedesktop.org/software/systemd/man/systemd.time.html for a complete list of allowed time span values.

user
Ruby Type: String | Default Value: root

The name of the user that Chef Infra Client runs as.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chef_client_systemd_timer resource in recipes:

Setup Chef Infra Client to run using the default 30 minute cadence:

chef_client_systemd_timer "Run Chef Infra Client as a systemd timer"

Run Chef Infra Client every 1 hour:

chef_client_systemd_timer "Run Chef Infra Client every 1 hour" do
  interval "1hr"
end

Run Chef Infra Client with extra options passed to the client:

chef_client_systemd_timer "Run an override recipe" do
  daemon_options ["--override-runlist mycorp_base::default"]
end

chef_client_trusted_certificate resource

chef_client_trusted_certificate resource page

Use the chef_client_trusted_certificate resource to add certificates to Chef Infra Client’s trusted certificate directory. This allows the Chef Infra Client to communicate with internal encrypted resources without errors.

New in Chef Infra Client 16.5.

Syntax


The full syntax for all of the properties that are available to the chef_client_trusted_certificate resource is:

chef_client_trusted_certificate 'name' do
  cert_name        String # default value: 'name' unless specified
  certificate      String
  action           Symbol # defaults to :add if not specified
end

where:

  • chef_client_trusted_certificate is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • cert_name and certificate are the properties available to this resource.

Actions


The chef_client_trusted_certificate resource has the following actions:

:add
Add the trusted certificate
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove the trusted certificate

Properties


The chef_client_trusted_certificate resource has the following properties:

cert_name
Ruby Type: String | Default Value: The resource block's name

The name to use for the certificate file on disk. If not provided the name of the resource block will be used instead.

certificate
Ruby Type: String | REQUIRED

The text of the certificate file including the BEGIN/END comment lines.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chef_client_trusted_certificate resource in recipes:

Trust a self signed certificate:

chef_client_trusted_certificate 'self-signed.badssl.com' do
  certificate <<~CERT
  -----BEGIN CERTIFICATE-----
  MIIDeTCCAmGgAwIBAgIJAPziuikCTox4MA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV
  BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNp
  c2NvMQ8wDQYDVQQKDAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTAeFw0x
  OTEwMDkyMzQxNTJaFw0yMTEwMDgyMzQxNTJaMGIxCzAJBgNVBAYTAlVTMRMwEQYD
  VQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ8wDQYDVQQK
  DAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTCCASIwDQYJKoZIhvcNAQEB
  BQADggEPADCCAQoCggEBAMIE7PiM7gTCs9hQ1XBYzJMY61yoaEmwIrX5lZ6xKyx2
  PmzAS2BMTOqytMAPgLaw+XLJhgL5XEFdEyt/ccRLvOmULlA3pmccYYz2QULFRtMW
  hyefdOsKnRFSJiFzbIRMeVXk0WvoBj1IFVKtsyjbqv9u/2CVSndrOfEk0TG23U3A
  xPxTuW1CrbV8/q71FdIzSOciccfCFHpsKOo3St/qbLVytH5aohbcabFXRNsKEqve
  ww9HdFxBIuGa+RuT5q0iBikusbpJHAwnnqP7i/dAcgCskgjZjFeEU4EFy+b+a1SY
  QCeFxxC7c3DvaRhBB0VVfPlkPz0sw6l865MaTIbRyoUCAwEAAaMyMDAwCQYDVR0T
  BAIwADAjBgNVHREEHDAaggwqLmJhZHNzbC5jb22CCmJhZHNzbC5jb20wDQYJKoZI
  hvcNAQELBQADggEBAGlwCdbPxflZfYOaukZGCaxYK6gpincX4Lla4Ui2WdeQxE95
  w7fChXvP3YkE3UYUE7mupZ0eg4ZILr/A0e7JQDsgIu/SRTUE0domCKgPZ8v99k3A
  vka4LpLK51jHJJK7EFgo3ca2nldd97GM0MU41xHFk8qaK1tWJkfrrfcGwDJ4GQPI
  iLlm6i0yHq1Qg1RypAXJy5dTlRXlCLd8ufWhhiwW0W75Va5AEnJuqpQrKwl3KQVe
  wGj67WWRgLfSr+4QG1mNvCZb2CkjZWmxkGPuoP40/y7Yu5OFqxP5tAjj4YixCYTW
  EVA0pmzIzgBg+JIe3PdRy27T0asgQW/F4TY61Yk=
  -----END CERTIFICATE-----
  CERT
end

chef_container resource

chef_container resource page

Use the chef_container resource to interact with container objects that exist on the Chef Infra Server.

Syntax


The syntax for using the chef_container resource in a recipe is as follows:

chef_container 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_container tells Chef Infra Client to use the Chef::Provider::ChefContainer provider during a Chef Infra Client run
  • name is the name of the resource block
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_container resource has the following actions:

:create
Default.
:delete
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_container resource has the following properties:

chef_server

The URL for the Chef Infra Server.

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

name

The name of the container.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples


This resource does not have any examples.

chef_data_bag resource

chef_data_bag resource page

Data bags store global variables as JSON data. Data bags are indexed for searching and can be loaded by a cookbook or accessed during a search.

Use the chef_data_bag resource to manage data bags.

Syntax


The syntax for using the chef_data_bag resource in a recipe is as follows:

chef_data_bag 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_data_bag tells Chef Infra Client to use the Chef::Provider::ChefDataBag provider during a Chef Infra Client run
  • name is the name of the resource block and also the name of the data bag
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_data_bag resource has the following actions:

:create
Default. Use to create a data bag.
:delete
Use to delete a data bag.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_data_bag resource has the following properties:

chef_server

The URL for the Chef Infra Server.

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

name

The name of the data bag.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples


This resource does not have any examples.

chef_data_bag_item resource

chef_data_bag_item resource page

A data bag is a container of related data bag items, where each individual data bag item is a JSON file. knife can load a data bag item by specifying the name of the data bag to which the item belongs and then the filename of the data bag item. The only structural requirement of a data bag item is that it must have an id:

{
  /* This is a supported comment style */
  // This style is also supported
  "id": "ITEM_NAME",
  "key": "value"
}

where

  • key and value are the key:value pair for each additional attribute within the data bag item
  • /* ... */ and // ... show two ways to add comments to the data bag item

Use the chef_data_bag_item resource to manage data bag items.

Syntax


The syntax for using the chef_data_bag_item resource in a recipe is as follows:

chef_data_bag_item 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_data_bag_item tells Chef Infra Client to use the Chef::Provider::ChefDataBagItem provider during a Chef Infra Client run
  • name is the name of the resource block and also the name of the data bag item
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_data_bag_item resource has the following actions:

:create
Default. Use to create a data bag item.
:delete
Use to delete a data bag item.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_data_bag_item resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines a data bag item completely. When true, any property not specified by this resource will be reset to default property values.

encrypt

Use to specify whether encryption is used for a data bag item.

encryption_version

The minimum required version of data bag encryption. Possible values: 0, 1, and 2. When all of the machines in an organization are running chef-client version 11.6 (or higher), it is recommended that this value be set to 2.

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

raw_data

Use to create a data bag from a local file from ./data_bags/bag_name/file.

raw_json

The data bag item as JSON data. For example:

{
  "id": "adam",
  "real_name": "Adam Brent Jacob"
}

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples


This resource does not have any examples.

chef_environment resource

chef_environment resource page

An environment is a way to map an organization’s real-life workflow to what can be configured and managed when using Chef Infra. This mapping is accomplished by setting attributes and pinning cookbooks at the environment level. With environments, you can change cookbook configurations depending on the system’s designation. For example, by designating different staging and production environments, you can then define the correct URL of a database server for each environment. Environments also allow organizations to move new cookbook releases from staging to production with confidence by stepping releases through testing environments before entering production.

Use the chef_environment resource to manage environments.

Syntax


The syntax for using the chef_environment resource in a recipe is as follows:

chef_environment 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_environment tells Chef Infra Client to use the Chef::Provider::ChefEnvironment provider during a Chef Infra Client run
  • name is the name of the resource block; when the name property is not specified as part of a recipe, name is also the name of the environment
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_environment resource has the following actions:

:create
Default. Use to create an environment.
:delete
Use to delete an environment.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_environment resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines an environment completely. When true, any property not specified by this resource will be reset to default property values.

cookbook_versions

The cookbook versions used with the environment. Default value: {}.

default_attributes

A default attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use default attributes as often as possible in cookbooks.

Default value: {}.

description

The description of the environment. This value populates the description field for the environment on the Chef Infra Server.

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

name

The name of the environment.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

override_attributes

An override attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than default, force_default, and normal attributes. An override attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses override attributes only when required.

Default value: {}.

raw_json

The environment as JSON data. For example:

{
  "name":"backend",
  "description":"",
  "cookbook_versions":{},
  "json_class":"Chef::Environment",
  "chef_type":"environment",
  "default_attributes":{},
  "override_attributes":{}
}

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples


This resource does not have any examples.

chef_gem resource

chef_gem resource page

Use the chef_gem resource to install a gem only for the instance of Ruby that is dedicated to the chef-client. When a gem is installed from a local file, it must be added to the node using the remote_file or cookbook_file resources.

The chef_gem resource works with all of the same properties and options as the gem_package resource, but does not accept the gem_binary property because it always uses the CurrentGemEnvironment under which the chef-client is running. In addition to performing actions similar to the gem_package resource, the chef_gem resource does the following:

  • Runs its actions immediately, before convergence, allowing a gem to be used in a recipe immediately after it is installed.
  • Runs Gem.clear_paths after the action, ensuring that gem is aware of changes so that it can be required immediately after it is installed.

Warning

The chef_gem and gem_package resources are both used to install Ruby gems. For any machine on which Chef Infra Client is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is available only to Chef Infra Client. Use the chef_gem resource to install gems into the instance of Ruby that is dedicated to Chef Infra Client. Use the gem_package resource to install all other gems (i.e. install gems system-wide).

Syntax


The full syntax for all of the properties that are available to the chef_gem resource is:

chef_gem 'name' do
  clear_sources               true, false
  gem_binary                  String
  include_default_source      true, false
  options                     String, Hash, Array
  package_name                String
  source                      String, Array
  timeout                     String, Integer
  version                     String
  action                      Symbol # defaults to :install if not specified
end

where:

  • chef_gem is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • clear_sources, gem_binary, include_default_source, options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The chef_gem resource has the following actions:

:install
Default. Install a gem. If a version is specified, install the specified version of the gem.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:purge
Purge a gem. This action typically removes the configuration files as well as the gem.
:reconfig
Reconfigure a gem. This action requires a response file.
:remove
Remove a gem.
:upgrade
Install a gem and/or ensure that a gem is the latest version.

Properties


The chef_gem resource has the following properties:

clear_sources
Ruby Type: true, false | Default Value: false

Set to true to download a gem from the path specified by the source property (and not from RubyGems).

gem_binary
Ruby Type: String | Default Value: The `gem` binary included with Chef Infra Client.

The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by Chef Infra Client will be used.

include_default_source
Ruby Type: true, false

Set to false to not include Chef::Config[:rubygems_url] in the sources.

New in Chef Client 13.0

options
Ruby Type: String, Hash, Array

Options for the gem install, either a Hash or a String. When a hash is given, the options are passed to Gem::DependencyInstaller.new, and the gem will be installed via the gems API. When a String is given, the gem will be installed by shelling out to the gem command. Using a Hash of options with an explicit gem_binary will result in undefined behavior.

package_name
Ruby Type: String

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String, Array

Optional. The URL, or list of URLs, at which the gem package is located. This list is added to the source configured in Chef::Config[:rubygems_url] (see also include_default_source) to construct the complete list of rubygems sources. Users in an ‘airgapped’ environment should set Chef::Config[:rubygems_url] to their local RubyGems mirror.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chef_gem resource in recipes:

Compile time vs. converge time installation of gems

To install a gem while Chef Infra Client is configuring the node (the converge phase), set the compile_time property to false:

chef_gem 'right_aws' do
  compile_time false
  action :install
end

To install a gem while the resource collection is being built (the compile phase), set the compile_time property to true:

chef_gem 'right_aws' do
  compile_time true
  action :install
end

Install MySQL gem into Chef Infra Client*

apt_update

build_essential 'install compilation tools' do
  compile_time true
end

chef_gem 'mysql'

chef_group resource

chef_group resource page

Use the chef_group resource to interact with group objects that exist on the Chef server.

Syntax


The syntax for using the chef_group resource in a recipe is as follows:

chef_group 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_group tells Chef Infra Client to use the Chef::Provider::ChefGroup provider during a Chef Infra Client run
  • name is the name of the resource block
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_group resource has the following actions:

:create
Default.
:delete
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_group resource has the following properties:

chef_server

The URL for the Chef server.

clients

complete

Use to specify if this resource defines a chef-client completely. When true, any property not specified by this resource will be reset to default property values.

groups

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

raw_json

The group as JSON data. For example:

{
  :groupname => "chef"
}

remove_clients

remove_groups

remove_users

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

users

Examples


This resource does not have any examples.

chef_handler resource

chef_handler resource page

Use the chef_handler resource to enable handlers during a Chef Infra Client run. The resource allows arguments to be passed to Chef Infra Client, which then applies the conditions defined by the custom handler to the node attribute data collected during a Chef Infra Client run, and then processes the handler based on that data. The chef_handler resource is typically defined early in a node’s run-list (often being the first item). This ensures that all of the handlers will be available for the entire Chef Infra Client run.

New in Chef Infra Client 14.0.

Handler Types

There are three types of handlers:

HandlerDescription
exceptionAn exception handler is used to identify situations that have caused a Chef Infra Client run to fail. An exception handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the chef_handler resource to a node's run-list. An exception handler runs when the failed? property for the run_status object returns true.
reportA report handler is used when a Chef Infra Client run succeeds and reports back on certain details about that Chef Infra Client run. A report handler can be loaded at the start of a Chef Infra Client run by adding a recipe that contains the chef_handler resource to a node's run-list. A report handler runs when the success? property for the run_status object returns true.
startA start handler is used to run events at the beginning of a Chef Infra Client run. A start handler can be loaded at the start of a Chef Infra Client run by adding the start handler to the start_handlers setting in the client.rb file or by installing the gem that contains the start handler by using the chef_gem resource in a recipe in the chef-client cookbook. (A start handler may not be loaded using the chef_handler resource.)

Exception / Report

Exception and report handlers are used to trigger certain behaviors in response to specific situations, typically identified during a Chef Infra Client run.

  • An exception handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run fails.
  • A report handler is used to trigger behaviors when a defined aspect of a Chef Infra Client run is successful.

Both types of handlers can be used to gather data about a Chef Infra Client run and can provide rich levels of data about all types of usage, which can be used later for trending and analysis across the entire organization.

Exception and report handlers are made available to a Chef Infra Client run in one of the following ways:

  • By adding the chef_handler resource to a recipe, and then adding that recipe to the run-list for a node. (The chef_handler resource is available from the chef_handler cookbook.)
  • By adding the handler to one of the following settings in the node’s client.rb file: exception_handlers and/or report_handlers

The chef_handler resource allows exception and report handlers to be enabled from within recipes, which can then added to the run-list for any node on which the exception or report handler should run. The chef_handler resource is available from the chef_handler cookbook.

To use the chef_handler resource in a recipe, add code similar to the following:

chef_handler 'name_of_handler' do
  source '/path/to/handler/handler_name'
  action :enable
end

For example, a handler for Growl needs to be enabled at the beginning of a Chef Infra Client run:

chef_gem 'chef-handler-growl'

and then is activated in a recipe by using the chef_handler resource:

chef_handler 'Chef::Handler::Growl' do
  source 'chef/handler/growl'
  action :enable
end

Start

A start handler is not loaded into a Chef Infra Client run from a recipe, but is instead listed in the client.rb file using the start_handlers attribute. The start handler must be installed on the node and be available to Chef Infra Client prior to the start of a Chef Infra Client run. Use the chef-client cookbook to install the start handler.

Start handlers are made available to a Chef Infra Client run in one of the following ways:

  • By adding a start handler to the chef-client cookbook, which installs the handler on the node so that it is available to Chef Infra Client at the start of a Chef Infra Client run
  • By adding the handler to one of the following settings in the node’s client.rb file: start_handlers

The chef-client cookbook can be configured to automatically install and configure gems that are required by a start handler. For example:

node.override['chef_client']['load_gems']['chef-reporting'] = {
  :require_name => 'chef_reporting',
  :action => :install
}

node.override['chef_client']['config']['start_handlers'] = [
  {
    :class => 'Chef::Reporting::StartHandler',
    :arguments => []
  }
]

include_recipe 'chef-client::config'

Syntax


A chef_handler resource block enables handlers during a chef-client run. Two handlers—JsonFile and ErrorReport—are built into Chef:

chef_handler 'Chef::Handler::JsonFile' do
  source 'chef/handler/json_file'
  arguments :path => '/var/chef/reports'
  action :enable
end

and:

chef_handler 'Chef::Handler::ErrorReport' do
  source 'chef/handler/error_report'
  action :enable
end

show how to enable those handlers in a recipe.

The full syntax for all of the properties that are available to the chef_handler resource is:

chef_handler 'name' do
  arguments       Array, Hash
  class_name      String # default value: 'name' unless specified
  source          String
  type            Hash # default value: {"report"=>true, "exception"=>true}
  action          Symbol # defaults to :enable if not specified
end

where:

  • chef_handler is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • arguments, class_name, source, and type are the properties available to this resource.

Actions


The chef_handler resource has the following actions:

:disable
Disable the handler for the current chef-client run on the current node.
:enable
Enable the handler for the current chef-client run on the current node.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_handler resource has the following properties:

arguments
Ruby Type: Array, Hash

An array of arguments that are passed to the initializer for the handler class. For example:

arguments :key1 => 'val1'

or:

arguments [:key1 => 'val1', :key2 => 'val2']

class_name
Ruby Type: String | Default Value: The resource block's name

The name of the handler class. This can be module name-spaced.

source
Ruby Type: String

The full path to the handler file. Can also be a gem path if the handler ships as part of a Ruby gem.

type
Ruby Type: Hash | Default Value: {"report"=>true, "exception"=>true}

The type of handler to register as, i.e. :report, :exception or both.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Custom Handlers

A custom handler can be created to support any situation. The easiest way to build a custom handler:

  1. Download the chef_handler cookbook
  2. Create a custom handler
  3. Write a recipe using the chef_handler resource
  4. Add that recipe to a node’s run-list, often as the first recipe in that run-list

Syntax

The syntax for a handler can vary, depending on what the the situations the handler is being asked to track, the type of handler being used, and so on. All custom exception and report handlers are defined using Ruby and must be a subclass of the Chef::Handler class.

require 'chef/log'

module ModuleName
  class HandlerName < Chef::Handler
    def report
      # Ruby code goes here
    end
  end
end

where:

  • require ensures that the logging functionality of Chef Infra Client is available to the handler
  • ModuleName is the name of the module as it exists within the Chef library
  • HandlerName is the name of the handler as it is used in a recipe
  • report is an interface that is used to define the custom handler

For example, the following shows a custom handler that sends an email that contains the exception data when a Chef Infra Client run fails:

require 'net/smtp'

module OrgName
  class SendEmail < Chef::Handler
    def report
      if run_status.failed? then
        message  = "From: sender_name <sender@example.com>\n"
        message << "To: recipient_address <recipient@example.com>\n"
        message << "Subject: chef-client Run Failed\n"
        message << "Date: #{Time.now.rfc2822}\n\n"
        message << "Chef run failed on #{node.name}\n"
        message << "#{run_status.formatted_exception}\n"
        message << Array(backtrace).join('\n')
        Net::SMTP.start('your.smtp.server', 25) do |smtp|
          smtp.send_message message, 'sender@example', 'recipient@example'
        end
      end
    end
  end
end

and then is used in a recipe like:

send_email 'blah' do
  # recipe code
end

report Interface

The report interface is used to define how a handler will behave and is a required part of any custom handler. The syntax for the report interface is as follows:

def report
  # Ruby code
end

The Ruby code used to define a custom handler will vary significantly from handler to handler. Chef Infra Client includes two default handlers: error_report and json_file. Their use of the report interface is shown below.

The error_report handler:

require 'chef/handler'
require 'chef/resource/directory'

class Chef
  class Handler
    class ErrorReport < ::Chef::Handler
      def report
        Chef::FileCache.store('failed-run-data.json', Chef::JSONCompat.to_json_pretty(data), 0640)
        Chef::Log.fatal("Saving node information to #{Chef::FileCache.load('failed-run-data.json', false)}")
      end
    end
 end
end

The json_file handler:

require 'chef/handler'
require 'chef/resource/directory'

class Chef
  class Handler
    class JsonFile < ::Chef::Handler
      attr_reader :config
      def initialize(config={})
        @config = config
        @config[:path] ||= '/var/chef/reports'
        @config
      end
      def report
        if exception
          Chef::Log.error('Creating JSON exception report')
        else
          Chef::Log.info('Creating JSON run report')
        end
        build_report_dir
        savetime = Time.now.strftime('%Y%m%d%H%M%S')
        File.open(File.join(config[:path], 'chef-run-report-#{savetime}.json'), 'w') do |file|
          run_data = data
          run_data[:start_time] = run_data[:start_time].to_s
          run_data[:end_time] = run_data[:end_time].to_s
          file.puts Chef::JSONCompat.to_json_pretty(run_data)
        end
      end
      def build_report_dir
        unless File.exist?(config[:path])
          FileUtils.mkdir_p(config[:path])
          File.chmod(00700, config[:path])
        end
      end
    end
  end
end

Optional Interfaces

The following interfaces may be used in a handler in the same way as the report interface to override the default handler behavior in Chef Infra Client. That said, the following interfaces are not typically used in a handler and, for the most part, are completely unnecessary for a handler to work properly and/or as desired.

data

The data method is used to return the Hash representation of the run_status object. For example:

def data
  @run_status.to_hash
end

run_report_safely

The run_report_safely method is used to run the report handler, rescuing and logging errors that may arise as the handler runs and ensuring that all handlers get a chance to run during a Chef Infra Client run (even if some handlers fail during that run). In general, this method should never be used as an interface in a custom handler unless this default behavior simply must be overridden.

def run_report_safely(run_status)
  run_report_unsafe(run_status)
rescue Exception => e
  Chef::Log.error('Report handler #{self.class.name} raised #{e.inspect}')
  Array(e.backtrace).each { |line| Chef::Log.error(line) }
ensure
  @run_status = nil
end

run_report_unsafe

The run_report_unsafe method is used to run the report handler without any error handling. This method should never be used directly in any handler, except during testing of that handler. For example:

def run_report_unsafe(run_status)
  @run_status = run_status
  report
end

run_status Object

The run_status object is initialized by Chef Infra Client before the report interface is run for any handler. The run_status object keeps track of the status of a Chef Infra Client run and will contain some (or all) of the following properties:

PropertyDescription
all_resourcesA list of all resources that are included in the resource_collection property for the current Chef Infra Client run.
backtraceA backtrace associated with the uncaught exception data that caused a Chef Infra Client run to fail, if present; nil for a successful Chef Infra Client run.
elapsed_timeThe amount of time between the start (start_time) and end (end_time) of a Chef Infra Client run.
end_timeThe time at which a Chef Infra Client run ended.
exceptionThe uncaught exception data which caused a Chef Infra Client run to fail; nil for a successful Chef Infra Client run.
failed?Show that a Chef Infra Client run has failed when uncaught exceptions were raised during a Chef Infra Client run. An exception handler runs when the failed? indicator is true.
nodeThe node on which a Chef Infra Client run occurred.
run_contextAn instance of the Chef::RunContext object; used by Chef Infra Client to track the context of the run; provides access to the cookbook_collection, resource_collection, and definitions properties.
start_timeThe time at which a Chef Infra Client run started.
success?Show that a Chef Infra Client run succeeded when uncaught exceptions were not raised during a Chef Infra Client run. A report handler runs when the success? indicator is true.
updated_resourcesA list of resources that were marked as updated as a result of a Chef Infra Client run.

Note

These properties are not always available. For example, a start handler runs at the beginning of Chef Infra Client run, which means that properties like end_time and elapsed_time are still unknown and will be unavailable to the run_status object.

Examples


The following examples demonstrate various approaches for using the chef_handler resource in recipes:

Enable the ‘MyHandler’ handler

The following example shows how to enable a fictional ‘MyHandler’ handler which is located on disk at /etc/chef/my_handler.rb. The handler will be configured to run with Chef Infra Client and will be passed values to the handler’s initializer method:

chef_handler 'MyHandler' do
  source '/etc/chef/my_handler.rb' # the file should already be at this path
  arguments path: '/var/chef/reports'
  action :enable
end

Enable handlers during the compile phase

chef_handler 'Chef::Handler::JsonFile' do
  source 'chef/handler/json_file'
  arguments path: '/var/chef/reports'
  action :enable
  compile_time true
end

Handle only exceptions

chef_handler 'Chef::Handler::JsonFile' do
  source 'chef/handler/json_file'
  arguments path: '/var/chef/reports'
  type exception: true
  action :enable
end

Cookbook Versions (a custom handler)

@juliandunn created a custom report handler that logs all of the cookbooks and cookbook versions that were used during a Chef Infra Client run, and then reports after the run is complete.

cookbook_versions.rb:

The following custom handler defines how cookbooks and cookbook versions that are used during a Chef Infra Client run will be compiled into a report using the Chef::Log class in Chef Infra Client:

require 'chef/log'

module Chef
  class CookbookVersionsHandler < Chef::Handler
    def report
      cookbooks = run_context.cookbook_collection
      Chef::Log.info('Cookbooks and versions run: #{cookbooks.map {|x| x.name.to_s + ' ' + x.version }}')
    end
  end
end

default.rb:

The following recipe is added to the run-list for every node on which a list of cookbooks and versions will be generated as report output after every Chef Infra Client run.

cookbook_file '/etc/chef/cookbook_versions.rb' do
  source 'cookbook_versions.rb'
  action :create
end

chef_handler 'Chef::CookbookVersionsHandler' do
  source '/etc/chef/cookbook_versions.rb'
  type report: true
  action :enable
end

This recipe will generate report output similar to the following:

[2013-11-26T03:11:06+00:00] INFO: Chef Infra Client Run complete in 0.300029878 seconds [2013-11-26T03:11:06+00:00] INFO: Running report handlers [2013-11-26T03:11:06+00:00] INFO: Cookbooks and versions run: [“cookbook_versions_handler 1.0.0”] [2013-11-26T03:11:06+00:00] INFO: Report handlers complete


**JsonFile Handler**

The JsonFile handler is available from the `chef_handler` cookbook and can be used with exceptions and reports. It serializes run status data to a JSON file. This handler may be enabled in one of the following ways.

By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run:

```ruby
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 name of the node.

normal_attributes

A normal attribute is a setting that persists in the node object. A normal attribute has a higher attribute precedence than a default attribute.

Default value: {}.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

override_attributes

An override attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than default, force_default, and normal attributes. An override attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses override attributes only when required.

Default value: {}.

raw_json

The node as JSON data. For example:

{
  "overrides": {},
  "name": "latte",
  "chef_type": "node",
  "json_class": "Chef::Node",
  "attributes": {
    "hardware_type": "laptop"
  },
  "run_list": [
    "recipe[apache2]"
  ],
  "defaults": {}
}

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

run_list

A comma-separated list of roles and/or recipes to be applied. Default value: []. For example: ["recipe[default]","recipe[apache2]"]

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples


This resource does not have any examples.

chef_organization resource

chef_organization resource page

Use the chef_organization resource to interact with organization objects that exist on the Chef Infra Server.

Syntax


The syntax for using the chef_organization resource in a recipe is as follows:

chef_organization 'name' do
  attribute 'value' # see attributes section below
  ...
  action :action # see actions section below
end

where:

  • chef_organization tells Chef Infra Client to use the Chef::Provider::ChefOrganization provider during a Chef Infra Client run
  • name is the name of the resource block
  • attribute is zero (or more) of the attributes that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_organization resource has the following actions:

:create
Default.
:delete
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_organization resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines an organization completely. When true, any property not specified by this resource will be reset to default property values.

full_name

The full name must begin with a non-white space character and must be between 1 and 1023 characters. For example: Chef Software, Inc..

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

invites

Use to specify a list of users to be invited to the organization. An invitation is sent to any user in this list who is not already a member of the organization.

members

Use to specify a list of users who MUST be members of the organization. These users will be added directly to the organization. The user who initiates this operation MUST also have permission to add users to the specified organization.

members_specified

Use to discover if a user is a member of an organization. Will return true if the user is a member.

name

The name must begin with a lower-case letter or digit, may only contain lower-case letters, digits, hyphens, and underscores, and must be between 1 and 255 characters. For example: chef.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

raw_json

The organization as JSON data. For example:

{
  "name": "chef",
  "full_name": "Chef Software, Inc",
  "guid": "f980d1asdfda0331235s00ff36862
  ...
}

remove_members

Use to remove the specified users from an organization. Invitations that have not been accepted will be cancelled.

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples


This resource does not have any examples.

chef_role resource

chef_role resource page

A role is a way to define certain patterns and processes that exist across nodes in an organization as belonging to a single job function. Each role consists of zero (or more) attributes and a run-list. Each node can have zero (or more) roles assigned to it. When a role is run against a node, the configuration details of that node are compared against the attributes of the role, and then the contents of that role’s run-list are applied to the node’s configuration details. When a Chef Infra Client runs, it merges its own attributes and run-lists with those contained within each assigned role.

Use the chef_role resource to manage roles.

Syntax


The syntax for using the chef_role resource in a recipe is as follows:

chef_role 'name' do
  attribute 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_role tells Chef Infra Client to use the Chef::Provider::ChefRole provider during a Chef Infra Client run
  • name is the name of the resource block; when the name property is not specified as part of a recipe, name is also the name of the role
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_role resource has the following actions:

:create
Default. Use to create a role.
:delete
Use to delete a role.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_role resource has the following properties:

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines a role completely. When true, any property not specified by this resource will be reset to default property values.

default_attributes

A default attribute is automatically reset at the start of every Chef Infra Client run and has the lowest attribute precedence. Use default attributes as often as possible in cookbooks.

Default value: {}.

description

The description of the role. This value populates the description field for the role on the Chef Infra Server.

env_run_lists

The environment-specific run-list for a role. Default value: []. For example: ["env_run_lists[webserver]"]

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

name

The name of the role.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

override_attributes

An override attribute is automatically reset at the start of every Chef Infra Client run and has a higher attribute precedence than default, force_default, and normal attributes. An override attribute is most often specified in a recipe, but can be specified in an attribute file, for a role, and/or for an environment. A cookbook should be authored so that it uses override attributes only when required.

Default value: {}.

raw_json

The role as JSON data. For example:

{
  "name": "webserver",
  "chef_type": "role",
  "json_class": "Chef::Role",
  "default_attributes": {},
  "description": "A webserver",
  "run_list": [
    "recipe[apache2]"
  ],
  "override_attributes": {}
}

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

run_list

A comma-separated list of roles and/or recipes to be applied. Default value: []. For example: ["recipe[default]","recipe[apache2]"]

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples


This resource does not have any examples.

chef_sleep resource

chef_sleep resource page

Use the chef_sleep resource to pause (sleep) for a number of seconds during a Chef Infra Client run. Only use this resource when a command or service exits successfully but is not ready for the next step in a recipe.

New in Chef Infra Client 15.5.

Syntax


The full syntax for all of the properties that are available to the chef_sleep resource is:

chef_sleep 'name' do
  seconds      String, Integer # default value: 'name' unless specified
  action       Symbol # defaults to :sleep if not specified
end

where:

  • chef_sleep is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • seconds is the property available to this resource.

Actions


The chef_sleep resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:sleep
Pause the Chef Infra Client run for a specified number of seconds.

Properties


The chef_sleep resource has the following properties:

seconds
Ruby Type: String, Integer | Default Value: The resource block's name

The number of seconds to sleep.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chef_sleep resource in recipes:

Sleep for 10 seconds:

chef_sleep '10'

Sleep for 10 seconds with a descriptive resource name for logging:

chef_sleep 'wait for the service to start' do
  seconds 10
end

Use a notification from another resource to sleep only when necessary:

service 'Service that is slow to start and reports as started' do
  service_name 'my_database'
  action :start
  notifies :sleep, chef_sleep['wait for service start']
end

chef_sleep 'wait for service start' do
  seconds 30
  action :nothing
end

chef_user resource

chef_user resource page

Use the chef_user resource to manage users.

Syntax


The syntax for using the chef_user resource in a recipe is as follows:

chef_user 'value' # see properties section below
  ...
  action :action # see actions section below
end

where:

  • chef_user tells Chef Infra Client to use the Chef::Provider::ChefUser provider during a Chef Infra Client run
  • name is the name of the resource block; when the name property is not specified as part of a recipe, name is also the name of the user
  • attribute is zero (or more) of the properties that are available for this resource
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state

Actions


The chef_user resource has the following actions:

:create
Default. Use to create a user.
:delete
Use to delete a user.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_user resource has the following properties:

admin

Create a client as an admin client. This is required for any user to access Chef as an administrator.

chef_server

The URL for the Chef Infra Server.

complete

Use to specify if this resource defines a user completely. When true, any property not specified by this resource will be reset to default property values.

email

The email address for the user.

external_authentication_uid

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

name

The name of the user.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

output_key_format

Use to specify the format of a public key. Possible values: pem, der, or openssh. Default value: openssh.

output_key_path

Use to specify the path to the location in which a public key will be written.

raw_json

The user as JSON data. For example:

{
  "name": "Robert Forster"
}

recovery_authentication_enabled

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source_key

Use to copy a public or private key, but apply a different format and password. Use in conjunction with source_key_pass_phrase and source_key_path.

source_key_pass_phrase

The pass phrase for the public key. Use in conjunction with source_key and source_key_path.

source_key_path

The path to the public key. Use in conjunction with source_key and source_key_pass_phrase.

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples


This resource does not have any examples.

chef_vault_secret resource

chef_vault_secret resource page

Use the chef_vault_secret resource to store secrets in Chef Vault items. Where possible and relevant, this resource attempts to map behavior and functionality to the knife vault sub-commands.

New in Chef Infra Client 16.0.

Syntax


The full syntax for all of the properties that are available to the chef_vault_secret resource is:

chef_vault_secret 'name' do
  admins           String, Array
  clients          String, Array
  data_bag         String
  environment      String
  id               String # default value: 'name' unless specified
  raw_data         Hash, ChefUtils::Mash # default value: {}
  search           String # default value: "*:*"
  action           Symbol # defaults to :create if not specified
end

where:

  • chef_vault_secret is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • admins, clients, data_bag, environment, id, raw_data, and search are the properties available to this resource.

Actions


The chef_vault_secret resource has the following actions:

:create
Create a Chef Vault data bag.
:create_if_missing
Create a Chef Vault data bag unless it already exists.
:delete
Delete a Chef Vault data bag if present.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chef_vault_secret resource has the following properties:

admins
Ruby Type: String, Array | REQUIRED

A list of admin users who should have access to the item. Corresponds to the ‘admin’ option when using the chef-vault knife plugin. Can be specified as a comma separated string or an array.

clients
Ruby Type: String, Array

A search query for the nodes’ API clients that should have access to the item.

data_bag
Ruby Type: String | REQUIRED

The data bag that contains the item.

environment
Ruby Type: String

The Chef environment of the data if storing per environment values.

id
Ruby Type: String | Default Value: The resource block's name

The name of the data bag item if it differs from the name of the resource block

raw_data
Ruby Type: Hash, ChefUtils::Mash | Default Value: {}

The raw data, as a Ruby Hash, that will be stored in the item.

search
Ruby Type: String | Default Value: *:*

Search query that would match the same used for the clients, gets stored as a field in the item.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chef_vault_secret resource in recipes:

To create a ‘foo’ item in an existing ‘bar’ data bag:

chef_vault_secret 'foo' do
  data_bag 'bar'
  raw_data({'auth' => 'baz'})
  admins 'jtimberman'
  search '*:*'
end

To allow multiple admins access to an item:

chef_vault_secret 'root-password' do
  admins 'jtimberman,paulmooring'
  data_bag 'secrets'
  raw_data({'auth' => 'DoNotUseThisPasswordForRoot'})
  search '*:*'
end

chocolatey_config resource

chocolatey_config resource page

Use the chocolatey_config resource to add or remove Chocolatey configuration keys.

New in Chef Infra Client 14.3.

Syntax


The full syntax for all of the properties that are available to the chocolatey_config resource is:

chocolatey_config 'name' do
  config_key      String # default value: 'name' unless specified
  value           String
  action          Symbol # defaults to :set if not specified
end

where:

  • chocolatey_config is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • config_key and value are the properties available to this resource.

Actions


The chocolatey_config resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:set
Default. Sets a Chocolatey config value.
:unset
Unsets a Chocolatey config value.

Properties


The chocolatey_config resource has the following properties:

config_key
Ruby Type: String | Default Value: The resource block's name

An optional property to set the config key name if it differs from the resource block’s name.

value
Ruby Type: String

The value to set.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chocolatey_config resource in recipes:

Set the Chocolatey cacheLocation config:

chocolatey_config 'Set cacheLocation config' do
  config_key 'cacheLocation'
  value 'C:	empoco'
end

Unset a Chocolatey config:

chocolatey_config 'BogusConfig' do
  action :unset
end

chocolatey_feature resource

chocolatey_feature resource page

Use the chocolatey_feature resource to enable and disable Chocolatey features.

New in Chef Infra Client 15.1.

Syntax


The full syntax for all of the properties that are available to the chocolatey_feature resource is:

chocolatey_feature 'name' do
  feature_name      String # default value: 'name' unless specified
  action            Symbol # defaults to :enable if not specified
end

where:

  • chocolatey_feature is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • feature_name is the property available to this resource.

Actions


The chocolatey_feature resource has the following actions:

:disable
Disable a Chocolatey Feature.
:enable
Enable a Chocolatey Feature.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The chocolatey_feature resource has the following properties:

feature_name
Ruby Type: String | Default Value: The resource block's name

The name of the Chocolatey feature to enable or disable.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chocolatey_feature resource in recipes:

Enable the checksumFiles Chocolatey feature

chocolatey_feature 'checksumFiles' do
  action :enable
end

Disable the checksumFiles Chocolatey feature

chocolatey_feature 'checksumFiles' do
  action :disable
end

chocolatey_package resource

chocolatey_package resource page

Use the chocolatey_package resource to manage packages using Chocolatey on the Microsoft Windows platform.

Warning

The chocolatey_package resource must be specified as chocolatey_package and cannot be shortened to package in a recipe.

Note

The Chocolatey package manager is not installed on Windows by default. You will need to install it prior to using this resource by adding the Chocolatey cookbook to your node’s run list.

New in Chef Infra Client 12.7.

Syntax


A chocolatey_package resource manages packages using Chocolatey on the Microsoft Windows platform. The simplest use of the chocolatey_package resource is:

chocolatey_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the chocolatey_package resource is:

chocolatey_package 'name' do
  list_options      String
  options           String, Array
  package_name      String, Array
  password          String
  returns           Integer, Array # default value: [0, 2]
  source            String
  timeout           String, Integer
  user              String
  version           String, Array
  action            Symbol # defaults to :install if not specified
end

where:

  • chocolatey_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • list_options, options, package_name, password, returns, source, timeout, user, and version are the properties available to this resource.

Actions


The chocolatey_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:reconfig
Reconfigure a package. This action requires a response file.
:remove
Remove a package.
:uninstall
Uninstall a package. Deprecated as of Chef 13.7
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The chocolatey_package resource has the following properties:

list_options
Ruby Type: String

One (or more) additional list options that are passed to the command.

New in Chef Infra Client 15.3

options
Ruby Type: String, Array

One (or more) additional options that are passed to the command.

package_name
Ruby Type: String, Array

The name of the package. Default value: the name of the resource block.

password
Ruby Type: String

The password to authenticate to the source.

New in Chef Infra Client 15.3

returns
Ruby Type: Integer, Array | Default Value: [0, 2]

The exit code(s) returned a chocolatey package that indicate success.

0: operation was successful, no issues detected

2: no results (enhanced)

NOTE: Starting in v0.10.12, if you have the feature ‘useEnhancedExitCodes’ turned on, then choco will provide enhanced exit codes that allow better integration and scripting.

The syntax for returns is:

returns [0, 2, 1605, 1614, 1641]

Updated in Chef Infra Client 15.3.

New in Chef Client 12.18

source
Ruby Type: String

The optional path to a package in the local file system or a reachable UNC path. Ensure that the path specified is to the folder containing the chocolatey package(s), not to the package itself.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

user
Ruby Type: String

The username to authenticate feeds.

New in Chef Infra Client 15.3

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chocolatey_package resource in recipes:

Install a Chocolatey package:

chocolatey_package 'name of package' do
  action :install
end

Install a package with options with Chocolatey’s --checksum option:

chocolatey_package 'name of package' do
  options '--checksum 1234567890'
  action :install
end

chocolatey_source resource

chocolatey_source resource page

Use the chocolatey_source resource to add, remove, enable, or disable Chocolatey sources.

New in Chef Infra Client 14.3.

Syntax


The full syntax for all of the properties that are available to the chocolatey_source resource is:

chocolatey_source 'name' do
  admin_only              true, false # default value: false
  allow_self_service      true, false # default value: false
  bypass_proxy            true, false # default value: false
  priority                Integer # default value: 0
  source                  String
  source_name             String # default value: 'name' unless specified
  action                  Symbol # defaults to :add if not specified
end

where:

  • chocolatey_source is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • admin_only, allow_self_service, bypass_proxy, priority, source, and source_name are the properties available to this resource.

Actions


The chocolatey_source resource has the following actions:

:add
Default. Adds a Chocolatey source.
:disable
Disables a Chocolatey source. New in Chef Infra Client 15.1.
:enable
Enables a Chocolatey source. New in Chef Infra Client 15.1.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Removes a Chocolatey source.

Properties


The chocolatey_source resource has the following properties:

admin_only
Ruby Type: true, false | Default Value: false

Whether or not to set the source to be accessible to only admins.

New in Chef Infra Client 15.1

allow_self_service
Ruby Type: true, false | Default Value: false

Whether or not to set the source to be used for self service.

New in Chef Infra Client 15.1

bypass_proxy
Ruby Type: true, false | Default Value: false

Whether or not to bypass the system’s proxy settings to access the source.

priority
Ruby Type: Integer | Default Value: 0

The priority level of the source.

source
Ruby Type: String

The source URL.

source_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the source name if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the chocolatey_source resource in recipes:

Add a Chocolatey source

chocolatey_source 'MySource' do
  source 'http://example.com/something'
  action :add
end

Remove a Chocolatey source

chocolatey_source 'MySource' do
  action :remove
end

cookbook_file resource

cookbook_file resource page

Use the cookbook_file resource to transfer files from a sub-directory of COOKBOOK_NAME/files/ to a specified path located on a host that is running Chef Infra Client. The file is selected according to file specificity, which allows different source files to be used based on the hostname, host platform (operating system, distro, or as appropriate), or platform version. Files that are located in the COOKBOOK_NAME/files/default sub-directory may be used on any platform.

During a Chef Infra Client run, the checksum for each local file is calculated and then compared against the checksum for the same file as it currently exists in the cookbook on the Chef Infra Server. A file is not transferred when the checksums match. Only files that require an update are transferred from the Chef Infra Server to a node.

Syntax


A cookbook_file resource block manages files by using files that exist within a cookbook’s /files directory. For example, to write the home page for an Apache website:

cookbook_file '/var/www/customers/public_html/index.php' do
  source 'index.php'
  owner 'web_admin'
  group 'web_admin'
  mode '0755'
  action :create
end

where:

  • '/var/www/customers/public_html/index.php' is path to the file to be created
  • 'index.php' is a file in the /files directory in a cookbook that is used to create that file (the contents of the file in the cookbook will become the contents of the file on the node)
  • owner, group, and mode define the permissions

The full syntax for all of the properties that are available to the cookbook_file resource is:

cookbook_file 'name' do
  atomic_update              true, false
  backup                     Integer, false # default value: 5
  cookbook                   String
  force_unlink               true, false # default value: false
  group                      String, Integer
  inherits                   true, false
  manage_symlink_source      true, false
  mode                       String, Integer
  owner                      String, Integer
  path                       String # default value: 'name' unless specified
  rights                     Hash
  source                     String, Array
  verify                     String, Block
  action                     Symbol # defaults to :create if not specified
end

where:

  • cookbook_file is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • atomic_update, backup, cookbook, force_unlink, group, inherits, manage_symlink_source, mode, owner, path, rights, source, and verify are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The cookbook_file resource has the following actions:

:create
Default. Create a file. If a file already exists (but does not match), update that file to match.
:create_if_missing
Create a file only if the file does not exist. When the file exists, nothing happens.
:delete
Delete a file.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:touch
Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the file resource.)

Properties


The cookbook_file resource has the following properties:

atomic_update
Ruby Type: true, false | Default Value: False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.

Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides file_atomic_update, which is a global setting found in the client.rb file.

backup
Ruby Type: Integer, false | Default Value: 5

The number of backups to be kept in /var/chef/backup (for UNIX- and Linux-based platforms) or C:/chef/backup (for the Microsoft Windows platform). Set to false to prevent backups from being kept.

cookbook
Ruby Type: String | Default Value: The current cookbook name

The cookbook in which a file is located (if it is not located in the current cookbook).

force_unlink
Ruby Type: true, false | Default Value: false

How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to true for Chef Infra Client delete the non-file target and replace it with the specified file. Set to false for Chef Infra Client to raise an error.

group
Ruby Type: Integer, String

A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

inherits
Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

manage_symlink_source
Ruby Type: true, false | Default Value: true

(with warning)

Change the behavior of the file resource if it is pointed at a symlink. When this value is set to true, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to false, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file.

The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning.

mode
Ruby Type: Integer, String

If mode is not specified and if the file already exists, the existing mode on the file is used. If mode is not specified, the file does not exist, and the :create action is specified, Chef Infra Client assumes a mask value of '0777' and then applies the umask for the system on which the file is to be created to the mask value. For example, if the umask on a system is '022', Chef Infra Client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

owner
Ruby Type: Integer, String

A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path
Ruby Type: String

The path to the destination at which a file is to be created. For example: file.txt.

Microsoft Windows: A path that begins with a forward slash (/) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended.

rights
Ruby Type: Integer, String

Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options.

source
Ruby Type: String, Array | Default Value: The resource block's name

The name of the file in COOKBOOK_NAME/files/default or the path to a file located in COOKBOOK_NAME/files. The path must include the file name and its extension. This can be used to distribute specific files depending upon the platform used - see File Specificity for more information.

verify
Ruby Type: String, Block

A block or a string that returns true or false. A string, when true is executed as a system command.

A block is arbitrary Ruby defined within the resource block by using the verify property. When a block is true, Chef Infra Client will continue to update the file as appropriate.

For example, this should return true:

cookbook_file '/tmp/baz' do
  verify { 1 == 1 }
end

This should return true:

cookbook_file '/etc/nginx.conf' do
  verify 'nginx -t -c %{path}'
end

This should return true:

cookbook_file '/tmp/bar' do
  verify { 1 == 1}
end

And this should return true:

cookbook_file '/tmp/foo' do
  verify do |path|
    true
  end
end

Whereas, this should return false:

cookbook_file '/tmp/turtle' do
  verify '/usr/bin/false'
end

If a string or a block return false, the Chef Infra Client run will stop and an error is returned.

Atomic File Updates

Atomic updates are used with file-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out.

Atomic updates are enabled by default. They can be managed globally using the file_atomic_update setting in the client.rb file. They can be managed on a per-resource basis using the atomic_update property that is available with the cookbook_file, file, remote_file, and template resources.

Note

On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the restorecon command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected.

Windows File Security

To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes. Access Control Lists (ACLs)

The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the rights property is as follows:

rights permission, principal, option_type => value

where

permission

Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control.

These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read.

(For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.)

principal

Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the SDDL string constants. Chef Infra Client does not need to know if a principal is a user or a group.

option_type

A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types:

Option TypeDescription
:applies_to_childrenSpecify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).
:applies_to_selfIndicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.
:one_level_deepIndicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, 'S-1-1-0'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
end

or:

rights :read, ['Administrators','Everyone']
rights :full_control, 'Users', :applies_to_children => true
rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true

Some other important things to know when using the rights attribute:

  • Only inherited rights remain. All existing explicit rights on the object are removed and replaced.
  • If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified.
  • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration.

Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
  deny_rights :read, ['Julian', 'Lewis']
end

or:

deny_rights :full_control, ['Sally']
Inheritance

By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The inherits property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory.

For example, the following example specifies the rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
end

and then the following example specifies how to use inheritance to deny access to the child directory:

directory 'C:\mordor\mount_doom' do
  rights :full_control, 'MORDOR\Sauron'
  inherits false # Sauron is the only person who should have any sort of access
end

If the deny_rights permission were to be used instead, something could slip through unless all users and groups were denied.

Another example also shows how to specify rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
  rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there
end

but then not use the inherits property to deny those rights on a child directory:

directory 'C:\mordor\mount_doom' do
  deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough
end

Because the inherits property is not specified, Chef Infra Client will default it to true, which will ensure that security settings for existing files remain unchanged.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

File Specificity

A cookbook is frequently designed to work across many platforms and is often required to distribute a specific file to a specific platform. A cookbook can be designed to support the distribution of files across platforms, while ensuring that the correct file ends up on each system.

The pattern for file specificity depends on two things: the lookup path and the source attribute. The first pattern that matches is used:

  1. /host-$fqdn/$source
  2. /$platform-$platform_version/$source
  3. /$platform/$source
  4. /default/$source
  5. /$source

Use an array with the source attribute to define an explicit lookup path. For example:

file '/conf.py' do
  source ['#{node.chef_environment}.py', 'conf.py']
end

The following example emulates the entire file specificity pattern by defining it as an explicit path:

file '/conf.py' do
  source %W{
    host-#{node['fqdn']}/conf.py
    #{node['platform']}-#{node['platform_version']}/conf.py
    #{node['platform']}/conf.py
    default/conf.py
  }
end

A cookbook may have a /files directory structure like this:

files/
   host-foo.example.com
   ubuntu-20.04
   ubuntu-20
   ubuntu
   redhat-8.2
   redhat-7.8
   ...
   default

and a resource that looks something like the following:

cookbook_file '/usr/local/bin/apache2_module_conf_generate.pl' do
  source 'apache2_module_conf_generate.pl'
  mode '0755'
  owner 'root'
  group 'root'
end

This resource is matched in the same order as the /files directory structure. For a node that is running Ubuntu 16.04, the second item would be the matching item and the location to which the file identified in the cookbook_file resource would be distributed:

host-foo.example.com/apache2_module_conf_generate.pl
ubuntu-20.04/apache2_module_conf_generate.pl
ubuntu-20/apache2_module_conf_generate.pl
ubuntu/apache2_module_conf_generate.pl
default/apache2_module_conf_generate.pl

If the apache2_module_conf_generate.pl file was located in the cookbook directory under files/host-foo.example.com/, the specified file(s) would only be copied to the machine with the domain name foo.example.com.

Host Notation

The naming of folders within cookbook directories must literally match the host notation used for file specificity matching. For example, if a host is named foo.example.com, the folder must be named host-foo.example.com.

Examples


The following examples demonstrate various approaches for using the cookbook_file resource in recipes:

Transfer a file

cookbook_file 'file.txt' do
  mode '0755'
end

Handle cookbook_file and package resources in the same recipe

When a cookbook_file resource and a package resource are both called from within the same recipe, use the flush_cache attribute to dump the in-memory Yum cache, and then use the repository immediately to ensure that the correct package is installed:

cookbook_file '/etc/yum.repos.d/custom.repo' do
  source 'custom'
  mode '0755'
end

package 'only-in-custom-repo' do
  action :install
  flush_cache [ :before ]
end

Install repositories from a file, trigger a command, and force the internal cache to reload

The following example shows how to install new Yum repositories from a file, where the installation of the repository triggers a creation of the Yum cache that forces the internal cache for Chef Infra Client to reload:

execute 'create-yum-cache' do
 command 'yum -q makecache'
 action :nothing
end

ruby_block 'reload-internal-yum-cache' do
  block do
    Chef::Provider::Package::Yum::YumCache.instance.reload
  end
  action :nothing
end

cookbook_file '/etc/yum.repos.d/custom.repo' do
  source 'custom'
  mode '0755'
  notifies :run, 'execute[create-yum-cache]', :immediately
  notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately
end

Use a case statement

The following example shows how a case statement can be used to handle a situation where an application needs to be installed on multiple platforms, but where the install directories are different paths, depending on the platform:

cookbook_file 'application.pm' do
  path case node['platform']
    when 'centos','redhat'
      '/usr/lib/version/1.2.3/dir/application.pm'
    when 'arch'
      '/usr/share/version/core_version/dir/application.pm'
    else
      '/etc/version/dir/application.pm'
    end
  source "application-#{node['languages']['perl']['version']}.pm"
  owner 'root'
  group 'root'
  mode '0755'
end

Manage dotfiles

The following example shows using the directory and cookbook_file resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to:

"files": {
  ".zshrc": {
    "mode": '0755',
    "source": "dot-zshrc"
    },
  ".bashrc": {
    "mode": '0755',
    "source": "dot-bashrc"
     },
  ".bash_profile": {
    "mode": '0755',
    "source": "dot-bash_profile"
    },
  }

and then the following resources manage the dotfiles:

if u.has_key?('files')
  u['files'].each do |filename, file_data|

  directory "#{home_dir}/#{File.dirname(filename)}" do
    recursive true
    mode '0755'
  end if file_data['subdir']

  cookbook_file "#{home_dir}/#{filename}" do
    source "#{u['id']}/#{file_data['source']}"
    owner 'u['id']'
    group 'group_id'
    mode 'file_data['mode']'
    ignore_failure true
    backup 0
  end
end

cron resource

cron resource page

Use the cron resource to manage cron entries for time-based job scheduling.

Warning

The cron resource should only be used to modify an entry in a crontab file. The cron_d resource directly manages cron.d files. This resource ships in Chef 14.4 or later and can also be found in the cron cookbook) for previous chef-client releases.

Syntax


A cron resource block manages cron entries. For example, to get a weekly cookbook report from the Chef Supermarket:

cron 'cookbooks_report' do
  action :create
  minute '0'
  hour '0'
  weekday '1'
  user 'chefio'
  mailto 'sysadmin@example.com'
  home '/srv/supermarket/shared/system'
  command %W{
    cd /srv/supermarket/current &&
    env RUBYLIB="/srv/supermarket/current/lib"
    RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}"
    bundle exec rake cookbooks_report
  }.join(' ')
end

The full syntax for all of the properties that are available to the cron resource is:

cron 'name' do
  command          String
  day              Integer, String # default value: "*"
  environment      Hash
  home             String
  hour             Integer, String # default value: "*"
  mailto           String
  minute           Integer, String # default value: "*"
  month            Integer, String # default value: "*"
  path             String
  shell            String
  time             Symbol
  time_out         Hash
  user             String # default value: "root"
  weekday          Integer, String, Symbol # default value: "*"
  action           Symbol # defaults to :create if not specified
end

where:

  • cron is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • command, day, environment, home, hour, mailto, minute, month, path, shell, time, time_out, user, and weekday are the properties available to this resource.

Actions


The cron resource has the following actions:

:create
Default. Create an entry in a cron table file (crontab). If an entry already exists (but does not match), update that entry to match.
:delete
Delete an entry from a cron table file (crontab).
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The cron resource has the following properties:

command
Ruby Type: String | REQUIRED

The command to be run, or the path to a file that contains the command to be run.

day
Ruby Type: Integer, String | Default Value: *

The day of month at which the cron entry should run (1 - 31).

environment
Ruby Type: Hash

A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of ({'ENV_VARIABLE' => 'VALUE'}). Note: These variables must exist for a command to be run successfully.

home
Ruby Type: String

Set the HOME environment variable.

hour
Ruby Type: Integer, String | Default Value: *

The hour at which the cron entry is to run (0 - 23).

mailto
Ruby Type: String

Set the MAILTO environment variable.

minute
Ruby Type: Integer, String | Default Value: *

The minute at which the cron entry should run (0 - 59).

month
Ruby Type: Integer, String | Default Value: *

The month in the year on which a cron entry is to run (1 - 12, jan-dec, or *).

path
Ruby Type: String

Set the PATH environment variable.

shell
Ruby Type: String

Set the SHELL environment variable.

time
Ruby Type: Symbol
Allowed Values: :annually, :daily, :hourly, :midnight, :monthly, :reboot, :weekly, :yearly

A time interval.

time_out
Ruby Type: Hash

A Hash of timeouts in the form of ({'OPTION' => 'VALUE'}). Accepted valid options are:

  • preserve-status (BOOL, default: ‘false’),
  • foreground (BOOL, default: ‘false’),
  • kill-after (in seconds),
  • signal (a name like ‘HUP’ or a number)

New in Chef Infra Client 15.7

user
Ruby Type: String | Default Value: root

The name of the user that runs the command. If the user property is changed, the original user for the crontab program continues to run until that crontab program is deleted. This property is not applicable on the AIX platform.

weekday
Ruby Type: Integer, String, Symbol | Default Value: *

The day of the week on which this entry is to run (0-7, mon-sun, monday-sunday, or *), where Sunday is both 0 and 7.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the cron resource in recipes:

Run a program at a specified interval

cron 'noop' do
  hour '5'
  minute '0'
  command '/bin/true'
end

Run an entry if a folder exists

cron 'ganglia_tomcat_thread_max' do
  command "/usr/bin/gmetric
    -n 'tomcat threads max'
    -t uint32
    -v '/usr/local/bin/tomcat-stat
    --thread-max'"
  only_if { ::File.exist?('/home/jboss') }
end

Run every Saturday, 8:00 AM

The following example shows a schedule that will run every hour at 8:00 each Saturday morning, and will then send an email to “admin@example.com” after each run.

cron 'name_of_cron_entry' do
  minute '0'
  hour '8'
  weekday '6'
  mailto 'admin@example.com'
  action :create
end

Run only in November

The following example shows a schedule that will run at 8:00 PM, every weekday (Monday through Friday), but only in November:

cron 'name_of_cron_entry' do
  minute '0'
  hour '20'
  day '*'
  month '11'
  weekday '1-5'
  action :create
end

cron_access resource

cron_access resource page

Use the cron_access resource to manage cron’s cron.allow and cron.deny files.

Note

This resource previously shipped in the cron cookbook as cron_manage, which it can still be used as for backwards compatibility with existing Chef Infra Client releases.

New in Chef Infra Client 14.4.

Syntax


The full syntax for all of the properties that are available to the cron_access resource is:

cron_access 'name' do
  user      String # default value: 'name' unless specified
  action    Symbol # defaults to :allow if not specified
end

where:

  • cron_access is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • user is the property available to this resource.

Actions


The cron_access resource has the following actions:

:allow
Default. Add the user to the cron.allow file.
:deny
Add the user to the cron.deny file.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The cron_access resource has the following properties:

user
Ruby Type: String | Default Value: The resource block's name

An optional property to set the user name if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the cron_access resource in recipes:

Add the mike user to cron.allow

cron_access 'mike'

Add the mike user to cron.deny

cron_access 'mike' do
  action :deny
end

Specify the username with the user property

cron_access 'Deny the jenkins user access to cron for security purposes' do
  user 'jenkins'
  action :deny
end

cron_d resource

cron_d resource page

Use the cron_d resource to manage cron job files in the /etc/cron.d directory.

Warning

Chef Infra Client also ships with the cron resource for managing the monolithic /etc/crontab file on platforms that lack cron.d support. See the cron resource for information on using that resource.

New in Chef Infra Client 14.4.

Syntax


A cron_d resource block manages cron.d files. For example, to get a weekly cookbook report from the Chef Supermarket:

cron_d 'cookbooks_report' do
  action :create
  minute '0'
  hour '0'
  weekday '1'
  user 'getchef'
  mailto 'sysadmin@example.com'
  home '/srv/supermarket/shared/system'
  command %W{
    cd /srv/supermarket/current &&
    env RUBYLIB="/srv/supermarket/current/lib"
    RAILS_ASSET_ID=`git rev-parse HEAD` RAILS_ENV="#{rails_env}"
    bundle exec rake cookbooks_report
  }.join(' ')
end

The full syntax for all of the properties that are available to the cron_d resource is:

cron_d 'name' do
  command               String
  comment               String
  cron_name             String # default value: 'name' unless specified
  day                   Integer, String # default value: "*"
  environment           Hash
  home                  String
  hour                  Integer, String # default value: "*"
  mailto                String
  minute                Integer, String # default value: "*"
  mode                  String, Integer # default value: "0600"
  month                 Integer, String # default value: "*"
  path                  String
  predefined_value      String
  random_delay          Integer
  shell                 String
  time_out              Hash
  user                  String # default value: "root"
  weekday               Integer, String, Symbol # default value: "*"
  action                Symbol # defaults to :create if not specified
end

where:

  • cron_d is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • command, comment, cron_name, day, environment, home, hour, mailto, minute, mode, month, path, predefined_value, random_delay, shell, time_out, user, and weekday are the properties available to this resource.

Actions


The cron_d resource has the following actions:

:create
Default. Add a cron definition file to /etc/cron.d.
:create_if_missing
Add a cron definition file to /etc/cron.d, but do not update an existing file.
:delete
Remove a cron definition file from /etc/cron.d if it exists.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The cron_d resource has the following properties:

command
Ruby Type: String | REQUIRED

The command to be run, or the path to a file that contains the command to be run.

comment
Ruby Type: String

A comment to place in the cron.d file.

cron_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the cron name if it differs from the resource block’s name.

day
Ruby Type: Integer, String | Default Value: *

The day of month at which the cron entry should run (1 - 31).

environment
Ruby Type: Hash

A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of ({'ENV_VARIABLE' => 'VALUE'}). Note: These variables must exist for a command to be run successfully.

home
Ruby Type: String

Set the HOME environment variable.

hour
Ruby Type: Integer, String | Default Value: *

The hour at which the cron entry is to run (0 - 23).

mailto
Ruby Type: String

Set the MAILTO environment variable.

minute
Ruby Type: Integer, String | Default Value: *

The minute at which the cron entry should run (0 - 59).

mode
Ruby Type: String, Integer | Default Value: "0600"

The octal mode of the generated crontab file.

month
Ruby Type: Integer, String | Default Value: *

The month in the year on which a cron entry is to run (1 - 12, jan-dec, or *).

path
Ruby Type: String

Set the PATH environment variable.

predefined_value
Ruby Type: String
Allowed Values: "@annually", "@daily", "@hourly", "@midnight", "@monthly", "@reboot", "@weekly", "@yearly"

Schedule your cron job with one of the special predefined value instead of ** * pattern.

random_delay
Ruby Type: Integer

Set the RANDOM_DELAY environment variable in the cron.d file.

shell
Ruby Type: String

Set the SHELL environment variable.

time_out
Ruby Type: Hash

A Hash of timeouts in the form of ({'OPTION' => 'VALUE'}). Accepted valid options are:

  • preserve-status (BOOL, default: ‘false’),
  • foreground (BOOL, default: ‘false’),
  • kill-after (in seconds),
  • signal (a name like ‘HUP’ or a number)

New in Chef Infra Client 15.7

user
Ruby Type: String | Default Value: root

The name of the user that runs the command.

weekday
Ruby Type: Integer, String, Symbol | Default Value: *

The day of the week on which this entry is to run (0-7, mon-sun, monday-sunday, or *), where Sunday is both 0 and 7.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the cron_d resource in recipes:

Run a program on the fifth hour of the day

cron_d 'noop' do
  hour '5'
  minute '0'
  command '/bin/true'
end

Run an entry if a folder exists

cron_d 'ganglia_tomcat_thread_max' do
  command "/usr/bin/gmetric
    -n 'tomcat threads max'
    -t uint32
    -v '/usr/local/bin/tomcat-stat
    --thread-max'"
  only_if { ::File.exist?('/home/jboss') }
end

Run an entry every Saturday, 8:00 AM

cron_d 'name_of_cron_entry' do
  minute '0'
  hour '8'
  weekday '6'
  mailto 'admin@example.com'
  command "/bin/true"
  action :create
end

Run an entry at 8:00 PM, every weekday (Monday through Friday), but only in November

cron_d 'name_of_cron_entry' do
  minute '0'
  hour '20'
  day '*'
  month '11'
  weekday '1-5'
  command "/bin/true"
  action :create
end

Remove a cron job by name:

cron_d 'job_to_remove' do
  action :delete
end

csh resource

csh resource page

Use the csh resource to execute scripts using the csh interpreter. This resource may also use any of the actions and properties that are available to the execute resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Syntax


A csh resource block executes scripts using csh:

csh 'hello world' do
  code <<-EOH
    echo "Hello world!"
    echo "Current directory: " $cwd
  EOH
end

where:

  • code specifies the command to run

The full syntax for all of the properties that are available to the csh resource is:

csh 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  path                       Array
  returns                    Integer, Array
  timeout                    Integer, Float
  user                       String, Integer
  umask                      String, Integer
  action                     Symbol # defaults to :run if not specified
end

where:

  • csh is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • code, creates, cwd, environment, flags, group, path, returns, timeout, user, and umask are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The csh resource has the following actions:

:nothing
Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it.
:run
Default. Run a script.

Properties


The csh resource has the following properties:

code
Ruby Type: String | REQUIRED

A quoted (” “) string of code to be executed.

creates
Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd
Ruby Type: String

The current working directory from which the command will be run.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags
Ruby Type: String

One or more command line flags that are passed to the interpreter when a command is invoked.

group
Ruby Type: String, Integer

The group name or group ID that must be changed before running a command.

returns
Ruby Type: Integer, Array | Default Value: 0

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match.

timeout
Ruby Type: Integer, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

user
Ruby Type: String, Integer

The user name or user ID that should be changed before running a command.

umask
Ruby Type: String, Integer

The file mode creation mask, or umask.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

directory resource

directory resource page

Use the directory resource to manage a directory, which is a hierarchy of folders that comprises all of the information stored on a computer. The root directory is the top-level, under which the rest of the directory is organized. The directory resource uses the name property to specify the path to a location in a directory. Typically, permission to access that location in the directory is required.

Syntax


A directory resource block declares a directory and the permissions needed on that directory. For example:

directory '/etc/apache2' do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

where:

  • '/etc/apache2' specifies the directory
  • owner, group, and mode define the permissions

The full syntax for all of the properties that are available to the directory resource is:

directory 'name' do
  group                      String, Integer
  inherits                   true, false
  mode                       String, Integer
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  recursive                  true, false
  rights                     Hash
  action                     Symbol # defaults to :create if not specified
end

where:

  • directory is the resource.
  • name is the name of the resource block; when the path property is not specified, name is also the path to the directory, from the root
  • action identifies the steps Chef Infra Client will take to bring the node into the desired state
  • group, inherits, mode, owner, path, recursive, and rights are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The directory resource has the following actions:

:create
Default. Create a directory. If a directory already exists (but does not match), update that directory to match.
:delete
Delete a directory.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The directory resource has the following properties:

group
Ruby Type: Integer, String

A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

inherits
Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

mode
Ruby Type: Integer, String

A quoted 3-5 character string that defines the octal mode. For example: '755', '0755', or 00755. If mode is not specified and if the directory already exists, the existing mode on the directory is used. If mode is not specified, the directory does not exist, and the :create action is specified, Chef Infra Client assumes a mask value of '0777', and then applies the umask for the system on which the directory is to be created to the mask value. For example, if the umask on a system is '022', Chef Infra Client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

owner
Ruby Type: Integer, String

A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path
Ruby Type: String | Default Value: The resource block's name

The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the name of the resource block. See “Syntax” section above for more information.

recursive
Ruby Type: true, false | Default Value: false

Create parent directories recursively and delete directories, subdirectories, and files recursively. The owner, group, and mode properties apply only to the leaf directory.

rights
Ruby Type: Integer, String

Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options.

Recursive Directories

The remote_directory resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the recursive attribute only applies group, mode, and owner attribute values to the remote directory itself and any inner directories the resource copies.

A directory structure:

/foo
  /bar
    /baz

The following example shows a way create a file in the /baz directory:

remote_directory "/foo/bar/baz" do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

But with this example, the group, mode, and owner attribute values will only be applied to /baz. Which is fine, if that’s what you want. But most of the time, when the entire /foo/bar/baz directory structure is not there, you must be explicit about each directory. For example:

%w[ /foo /foo/bar /foo/bar/baz ].each do |path|
  remote_directory path do
    owner 'root'
    group 'root'
    mode '0755'
  end
end

This approach will create the correct hierarchy—/foo, then /bar in /foo, and then /baz in /bar—and also with the correct attribute values for group, mode, and owner.

Windows File Security

To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes. Access Control Lists (ACLs)

The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the rights property is as follows:

rights permission, principal, option_type => value

where

permission

Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control.

These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read.

(For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.)

principal

Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the SDDL string constants. Chef Infra Client does not need to know if a principal is a user or a group.

option_type

A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types:

Option TypeDescription
:applies_to_childrenSpecify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).
:applies_to_selfIndicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.
:one_level_deepIndicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, 'S-1-1-0'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
end

or:

rights :read, ['Administrators','Everyone']
rights :full_control, 'Users', :applies_to_children => true
rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true

Some other important things to know when using the rights attribute:

  • Only inherited rights remain. All existing explicit rights on the object are removed and replaced.
  • If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified.
  • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration.

Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
  deny_rights :read, ['Julian', 'Lewis']
end

or:

deny_rights :full_control, ['Sally']
Inheritance

By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The inherits property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory.

For example, the following example specifies the rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
end

and then the following example specifies how to use inheritance to deny access to the child directory:

directory 'C:\mordor\mount_doom' do
  rights :full_control, 'MORDOR\Sauron'
  inherits false # Sauron is the only person who should have any sort of access
end

If the deny_rights permission were to be used instead, something could slip through unless all users and groups were denied.

Another example also shows how to specify rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
  rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there
end

but then not use the inherits property to deny those rights on a child directory:

directory 'C:\mordor\mount_doom' do
  deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough
end

Because the inherits property is not specified, Chef Infra Client will default it to true, which will ensure that security settings for existing files remain unchanged.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the directory resource in recipes:

Create a directory

directory '/tmp/something' do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

Create a directory in Microsoft Windows

directory "C:\\tmp\\something" do
  rights :full_control, "DOMAIN\\User"
  inherits false
  action :create
end

or:

directory 'C:\tmp\something' do
  rights :full_control, 'DOMAIN\User'
  inherits false
  action :create
end

Note

The difference between the two previous examples is the single- versus double-quoted strings, where if the double quotes are used, the backslash character (\) must be escaped using the Ruby escape character (which is a backslash).

  </div>
</div>

Create a directory recursively

%w{dir1 dir2 dir3}.each do |dir|
  directory "/tmp/mydirs/#{dir}" do
    mode '0755'
    owner 'root'
    group 'root'
    action :create
    recursive true
  end
end

Delete a directory

directory '/tmp/something' do
  recursive true
  action :delete
end

Set directory permissions using a variable

The following example shows how read/write/execute permissions can be set using a variable named user_home, and then for owners and groups on any matching node:

user_home = "/#{node[:matching_node][:user]}"

directory user_home do
  owner 'node[:matching_node][:user]'
  group 'node[:matching_node][:group]'
  mode '0755'
  action :create
end

where matching_node represents a type of node. For example, if the user_home variable specified {node[:nginx]...}, a recipe might look similar to:

user_home = "/#{node[:nginx][:user]}"

directory user_home do
  owner 'node[:nginx][:user]'
  group 'node[:nginx][:group]'
  mode '0755'
  action :create
end

Set directory permissions for a specific type of node

The following example shows how permissions can be set for the /certificates directory on any node that is running Nginx. In this example, permissions are being set for the owner and group properties as root, and then read/write permissions are granted to the root.

directory "#{node[:nginx][:dir]}/shared/certificates" do
  owner 'root'
  group 'root'
  mode '0755'
  recursive true
end

Reload the configuration

The following example shows how to reload the configuration of a chef-client using the remote_file resource to:

  • using an if statement to check whether the plugins on a node are the latest versions
  • identify the location from which Ohai plugins are stored
  • using the notifies property and a ruby_block resource to trigger an update (if required) and to then reload the client.rb file.
directory 'node[:ohai][:plugin_path]' do
  owner 'chef'
  recursive true
end

ruby_block 'reload_config' do
  block do
    Chef::Config.from_file('/etc/chef/client.rb')
  end
  action :nothing
end

if node[:ohai].key?(:plugins)
  node[:ohai][:plugins].each do |plugin|
    remote_file node[:ohai][:plugin_path] +"/#{plugin}" do
      source plugin
      owner 'chef'
      notifies :run, 'ruby_block[reload_config]', :immediately
    end
  end
end

Manage dotfiles

The following example shows using the directory and cookbook_file resources to manage dotfiles. The dotfiles are defined by a JSON data structure similar to:

"files": {
  ".zshrc": {
    "mode": '0755',
    "source": "dot-zshrc"
    },
  ".bashrc": {
    "mode": '0755',
    "source": "dot-bashrc"
     },
  ".bash_profile": {
    "mode": '0755',
    "source": "dot-bash_profile"
    },
  }

and then the following resources manage the dotfiles:

if u.has_key?('files')
  u['files'].each do |filename, file_data|

  directory "#{home_dir}/#{File.dirname(filename)}" do
    recursive true
    mode '0755'
  end if file_data['subdir']

  cookbook_file "#{home_dir}/#{filename}" do
    source "#{u['id']}/#{file_data['source']}"
    owner 'u['id']'
    group 'group_id'
    mode 'file_data['mode']'
    ignore_failure true
    backup 0
  end
end

dmg_package resource

dmg_package resource page

Use the dmg_package resource to install a package from a .dmg file. The resource will retrieve the dmg file from a remote URL, mount it using macOS’ hdidutil, copy the application (.app directory) to the specified destination (/Applications), and detach the image using hdiutil. The dmg file will be stored in the Chef::Config[:file_cache_path].

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the dmg_package resource is:

dmg_package 'name' do
  accept_eula          true, false # default value: false
  allow_untrusted      true, false # default value: false
  app                  String # default value: 'name' unless specified
  checksum             String
  destination          String # default value: "/Applications"
  dmg_name             String # default value: The value passed for the application name.
  dmg_passphrase       String
  file                 String
  headers              Hash
  owner                String, Integer
  package_id           String
  source               String
  type                 String # default value: "app"
  volumes_dir          String # default value: The value passed for the application name.
  action               Symbol # defaults to :install if not specified
end

where:

  • dmg_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • accept_eula, allow_untrusted, app, checksum, destination, dmg_name, dmg_passphrase, file, headers, owner, package_id, source, type, and volumes_dir are the properties available to this resource.

Actions


The dmg_package resource has the following actions:

:install
Default. Installs the application.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The dmg_package resource has the following properties:

accept_eula
Ruby Type: true, false | Default Value: false

Specify whether to accept the EULA. Certain dmg files require acceptance of EULA before mounting.

allow_untrusted
Ruby Type: true, false | Default Value: false

Allow installation of packages that do not have trusted certificates.

app
Ruby Type: String | Default Value: The resource block's name

The name of the application as it appears in the /Volumes directory if it differs from the resource block’s name.

checksum
Ruby Type: String

The sha256 checksum of the .dmg file to download.

destination
Ruby Type: String | Default Value: /Applications

The directory to copy the .app into.

dmg_name
Ruby Type: String | Default Value: The value passed for the application name.

The name of the .dmg file if it differs from that of the app, or if the name has spaces.

dmg_passphrase
Ruby Type: String

Specify a passphrase to be used to decrypt the .dmg file during the mount process.

file
Ruby Type: String

The absolute path to the .dmg file on the local system.

headers
Ruby Type: Hash

Allows custom HTTP headers (like cookies) to be set on the remote_file resource.

owner
Ruby Type: String, Integer

The user that should own the package installation.

package_id
Ruby Type: String

The package ID that is registered with pkgutil when a pkg or mpkg is installed.

source
Ruby Type: String

The remote URL that is used to download the .dmg file, if specified.

type
Ruby Type: String | Default Value: app
Allowed Values: "app", "mpkg", "pkg"

The type of package.

volumes_dir
Ruby Type: String | Default Value: The value passed for the application name.

The directory under /Volumes where the dmg is mounted if it differs from the name of the .dmg file.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the dmg_package resource in recipes:

Install Google Chrome via the DMG package:

dmg_package 'Google Chrome' do
  dmg_name 'googlechrome'
  source   'https://dl-ssl.google.com/chrome/mac/stable/GGRM/googlechrome.dmg'
  checksum '7daa2dc5c46d9bfb14f1d7ff4b33884325e5e63e694810adc58f14795165c91a'
  action   :install
end

Install Virtualbox from the .mpkg:

dmg_package 'Virtualbox' do
  source 'http://dlc.sun.com.edgesuite.net/virtualbox/4.0.8/VirtualBox-4.0.8-71778-OSX.dmg'
  type   'mpkg'
end

Install pgAdmin and automatically accept the EULA:

dmg_package 'pgAdmin3' do
  source   'http://wwwmaster.postgresql.org/redir/198/h/pgadmin3/release/v1.12.3/osx/pgadmin3-1.12.3.dmg'
  checksum '9435f79d5b52d0febeddfad392adf82db9df159196f496c1ab139a6957242ce9'
  accept_eula true
end

dnf_package resource

dnf_package resource page

Use the dnf_package resource to install, upgrade, and remove packages with DNF for Fedora and RHEL 8+. The dnf_package resource is able to resolve provides data for packages much like DNF can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides and library names.

New in Chef Infra Client 12.18.

Syntax


A dnf_package resource block manages a package on a node, typically by installing it. The simplest use of the dnf_package resource is:

dnf_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the dnf_package resource is:

dnf_package 'name' do
  arch              String, Array
  flush_cache       Hash # default value: {"before"=>false, "after"=>false}
  options           String, Array
  package_name      String, Array
  source            String
  timeout           String, Integer
  version           String, Array
  action            Symbol # defaults to :install if not specified
end

where:

  • dnf_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • arch, flush_cache, options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The dnf_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:lock
Locks the DNF package to a specific version.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:remove
Remove a package.
:unlock
Unlocks the DNF package so that it can be upgraded to a newer version.
:upgrade
Install a package and/or ensure that a package is the latest version. This action will ignore the version attribute.

Properties


The dnf_package resource has the following properties:

arch
Ruby Type: String, Array

The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name.

flush_cache
Ruby Type: Array

Flush the in-memory cache before or after a DNF operation that installs, upgrades, or removes a package. Default value: [ :before, :after ]. The value may also be a Hash: ( { :before => true/false, :after => true/false } ).

DNF automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while a Chef Infra Client run is in-progress.

As an array:

dnf_package 'some-package' do
  #...
  flush_cache [ :before ]
  #...
end

and as a Hash:

dnf_package 'some-package' do
  #...
  flush_cache( { :after => true } )
  #...
end

Note

The flush_cache property does not flush the local DNF cache! Use dnf tools—dnf clean metadata, dnf clean packages, dnf clean all—to clean the local DNF cache.

options
Ruby Type: String, Array

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded. This property is ignored when using the :upgrade action.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to:

  • Download the specified packages and versions via a single HTTP transaction
  • Update or install multiple packages with a single resource during a Chef Infra Client run

For example, installing multiple packages:

package %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(package1 package2)  do
  action :nothing
end

log 'call a notification' do
  notifies :install, 'package[package1, package2]', :immediately
end

Note

Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the package_name or version properties.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to:

  • Download the specified packages and versions via a single HTTP transaction
  • Update or install multiple packages with a single resource during a Chef Infra Client run

For example, installing multiple packages:

package %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(package1 package2)  do
  action :nothing
end

log 'call a notification' do
  notifies :install, 'package[package1, package2]', :immediately
end

Note

Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the package_name or version properties.

Examples


The following examples demonstrate various approaches for using the dnf_package resource in recipes:

Install an exact version

dnf_package 'netpbm = 10.35.58-8.el5'

Install a minimum version

dnf_package 'netpbm >= 10.35.58-8.el5'

Install a minimum version using the default action

dnf_package 'netpbm'

To install a package

dnf_package 'netpbm' do
  action :install
end

To install a partial minimum version

dnf_package 'netpbm >= 10'

To install a specific architecture

dnf_package 'netpbm' do
  arch 'i386'
end

or:

dnf_package 'netpbm.x86_64'

To install a specific version-release

dnf_package 'netpbm' do
  version '10.35.58-8.el5'
end

To install a specific version (even when older than the current)

dnf_package 'tzdata' do
  version '2011b-1.el5'
end

Handle cookbook_file and dnf_package resources in the same recipe

When a cookbook_file resource and a dnf_package resource are both called from within the same recipe, use the flush_cache attribute to dump the in-memory DNF cache, and then use the repository immediately to ensure that the correct package is installed:

cookbook_file '/etc/yum.repos.d/custom.repo' do
  source 'custom'
  mode '0755'
end

dnf_package 'only-in-custom-repo' do
  action :install
  flush_cache [ :before ]
end

dpkg_package resource

dpkg_package resource page

Use the dpkg_package resource to manage packages for the dpkg platform. When a package is installed from a local file, it must be added to the node using the remote_file or cookbook_file resources.

Syntax


A dpkg_package resource block manages a package on a node, typically by installing it. The simplest use of the dpkg_package resource is:

dpkg_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the dpkg_package resource is:

dpkg_package 'name' do
  options                      String, Array
  package_name                 String, Array
  response_file                String
  response_file_variables      Hash
  source                       String, Array
  timeout                      String, Integer
  version                      String, Array
  action                       Symbol # defaults to :install if not specified
end

where:

  • dpkg_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • options, package_name, response_file, response_file_variables, source, timeout, and version are the properties available to this resource.

Actions


The dpkg_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:remove
Remove a package.

Properties


The dpkg_package resource has the following properties:

options
Ruby Type: String, Array

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

response_file
Ruby Type: String

The direct path to the file used to pre-seed a package.

response_file_variables
Ruby Type: Hash

A Hash of response file variables in the form of {‘VARIABLE’ => ‘VALUE’}.

source
Ruby Type: String, Array

The path to a package in the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. 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 dpkg_package resource in recipes:

Install a package

dpkg_package 'wget_1.13.4-2ubuntu1.4_amd64.deb' do
  source '/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb'
  action :install
end

dsc_resource resource

dsc_resource resource page

Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing Unix and Linux-based machines. Windows PowerShell is a tool-agnostic platform that supports using Chef for configuration management.

Desired State Configuration (DSC) is a feature of Windows PowerShell that provides a set of language extensions, cmdlets, and resources that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell.

The dsc_resource resource allows any DSC resource to be used in a Chef recipe, as well as any custom resources that have been added to your Windows PowerShell environment. Microsoft frequently adds new resources to the DSC resource collection.

Warning

Using the dsc_resource has the following requirements:

  • Windows Management Framework (WMF) 5.0 (or higher)

  • The dsc_resource resource can only use binary- or script-based resources. Composite DSC resources may not be used.

    This is because composite resources aren’t “real” resources from the perspective of the Local Configuration Manager (LCM). Composite resources are used by the “configuration” keyword from the PSDesiredStateConfiguration module, and then evaluated in that context. When using DSC to create the configuration document (the Managed Object Framework (MOF) file) from the configuration command, the composite resource is evaluated. Any individual resources from that composite resource are written into the Managed Object Framework (MOF) document. As far as the Local Configuration Manager (LCM) is concerned, there is no such thing as a composite resource. Unless that changes, the dsc_resource resource and/or Invoke-DscResource command cannot directly use them.

Syntax


A dsc_resource resource block allows DSC resources to be used in a Chef recipe. For example, the DSC Archive resource:

Archive ExampleArchive {
  Ensure = "Present"
  Path = "C:\Users\Public\Documents\example.zip"
  Destination = "C:\Users\Public\Documents\ExtractionPath"
}

and then the same dsc_resource with Chef:

dsc_resource 'example' do
   resource :archive
   property :ensure, 'Present'
   property :path, "C:\Users\Public\Documents\example.zip"
   property :destination, "C:\Users\Public\Documents\ExtractionPath"
 end```

The full syntax for all of the properties that are available to the dsc_resource resource is:

dsc_resource 'name' do
  module_name                String
  module_version             String
  property                   Symbol
  reboot_action              Symbol # default value: :nothing
  resource                   Symbol
  timeout                    Integer
  action                     Symbol # defaults to :run if not specified
end

where:

  • dsc_resource 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.
  • property is zero (or more) properties in the DSC resource, where each property is entered on a separate line, :dsc_property_name is the case-insensitive name of that property, and "property_value" is a Ruby value to be applied by Chef Infra Client
  • module_name, module_version, property, reboot_action, resource, and timeout are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The dsc_resource resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:run
Default. Use to run the DSC configuration defined as defined in this resource.

Properties


The dsc_resource resource has the following properties:

module_name
Ruby Type: String

The name of the module from which a DSC resource originates. If this property is not specified, it will be inferred.

module_version
Ruby Type: String

The version number of the module to use. PowerShell 5.0.10018.0 (or higher) supports having multiple versions of a module installed. This should be specified along with the module_name.

property
Ruby Type: Symbol

A property from a Desired State Configuration (DSC) resource. Use this property multiple times, one for each property in the Desired State Configuration (DSC) resource. The format for this property must follow property :dsc_property_name, "property_value" for each DSC property added to the resource block.

The :dsc_property_name must be a symbol.

Use the following Ruby types to define property_value:

RubyWindows PowerShell
ArrayObject[]
Chef::Util::Powershell:PSCredentialPSCredential
Falsebool($false)
FixnumInteger
FloatDouble
HashHashtable
Truebool($true)

These are converted into the corresponding Windows PowerShell type during a Chef Infra Client run.

reboot_action
Ruby Type: Symbol | Default Value: :nothing
Allowed Values: :nothing :reboot_now :request_reboot

Use to request an immediate reboot or to queue a reboot using the :reboot_now (immediate reboot) or :request_reboot (queued reboot) actions built into the reboot resource.

resource
Ruby Type: Symbol

The name of the DSC resource. This value is case-insensitive and must be a symbol that matches the name of the DSC resource.

For built-in DSC resources, use the following values:

ValueDescription
:archiveUse to unpack archive (.zip) files.
:environmentUse to manage system environment variables.
:fileUse to manage files and directories.
:groupUse to manage local groups.
:logUse to log configuration messages.
:packageUse to install and manage packages.
:registryUse to manage registry keys and registry key values.
:scriptUse to run PowerShell script blocks.
:serviceUse to manage services.
:userUse to manage local user accounts.
:windowsfeatureUse to add or remove Windows features and roles.
:windowsoptionalfeatureUse to configure Microsoft Windows optional features.
:windowsprocessUse to configure Windows processes.

Any DSC resource may be used in a Chef recipe. For example, the DSC Resource Kit contains resources for configuring Active Directory components, such as xADDomain, xADDomainController, and xADUser. Assuming that these resources are available to Chef Infra Client, the corresponding values for the resource attribute would be: :xADDomain, :xADDomainController, and xADUser.

timeout
Ruby Type: Integer

The amount of time (in seconds) a command is to wait before timing out.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the dsc_resource resource in recipes:

Open a Zip file

dsc_resource 'example' do
   resource :archive
   property :ensure, 'Present'
   property :path, 'C:\Users\Public\Documents\example.zip'
   property :destination, 'C:\Users\Public\Documents\ExtractionPath'
 end

Manage users and groups

dsc_resource 'demogroupadd' do
  resource :group
  property :groupname, 'demo1'
  property :ensure, 'present'
end

dsc_resource 'useradd' do
  resource :user
  property :username, 'Foobar1'
  property :fullname, 'Foobar1'
  property :password, ps_credential('P@assword!')
  property :ensure, 'present'
end

dsc_resource 'AddFoobar1ToUsers' do
  resource :Group
  property :GroupName, 'demo1'
  property :MembersToInclude, ['Foobar1']
end

Create and register a windows service

The following example creates a windows service, defines it’s execution path, and prevents windows from starting the service in case the executable is not at the defined location:

dsc_resource 'NAME' do
  resource :service
  property :name, 'NAME'
  property :startuptype, 'Disabled'
  property :path, 'D:\\Sites\\Site_name\file_to_run.exe'
  property :ensure, 'Present'
  property :state, 'Stopped'
end

Create a test message queue

The following example creates a file on a node (based on one that is located in a cookbook), unpacks the MessageQueue.zip Windows PowerShell module, and then uses the dsc_resource to ensure that Message Queuing (MSMQ) sub-features are installed, a test queue is created, and that permissions are set on the test queue:

cookbook_file 'cMessageQueue.zip' do
  path "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip"
  action :create_if_missing
end

windows_zipfile "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" do
  source "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip"
  action :unzip
end

dsc_resource 'install-sub-features' do
  resource :windowsfeature
  property :ensure, 'Present'
  property :name, 'msmq'
  property :IncludeAllSubFeature, true
end

dsc_resource 'create-test-queue' do
  resource :cPrivateMsmqQueue
  property :ensure, 'Present'
  property :name, 'Test_Queue'
end

dsc_resource 'set-permissions' do
  resource :cPrivateMsmqQueuePermissions
  property :ensure, 'Present'
  property :name, 'Test_Queue_Permissions'
  property :QueueNames, 'Test_Queue'
  property :ReadUsers, node['msmq']['read_user']
end

Example to show usage of module properties

dsc_resource 'test-cluster' do
  resource :xCluster
  module_name 'xFailOverCluster'
  module_version '1.6.0.0'
  property :name, 'TestCluster'
  property :staticipaddress, '10.0.0.3'
  property :domainadministratorcredential, ps_credential('abcd')
end

dsc_script resource

dsc_script resource page

Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing Unix and Linux-based machines. Windows PowerShell is a tool-agnostic platform that supports using Chef for configuration management.

Desired State Configuration (DSC) is a feature of Windows PowerShell that provides a set of language extensions, cmdlets, and resources that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell.

Many DSC resources are comparable to built-in Chef Infra resources. For example, both DSC and Chef have file, package, and service resources. The dsc_script resource is most useful for those DSC resources that do not have a direct comparison to a resource in Chef, such as the Archive resource, a custom DSC resource, an existing DSC script that performs an important task, and so on. Use the dsc_script resource to embed the code that defines a DSC configuration directly within a Chef Infra recipe.

Note

Windows PowerShell 4.0 is required for using the dsc_script resource with Chef Infra.

Note

The WinRM service must be enabled. (Use winrm quickconfig to enable the service.)

Warning

The dsc_script resource may not be used in the same run-list with the dsc_resource. This is because the dsc_script resource requires that RefreshMode in the Local Configuration Manager be set to Push, whereas the dsc_resource resource requires it to be set to Disabled.

Syntax


A dsc_script resource block embeds the code that defines a DSC configuration directly within a Chef recipe:

dsc_script 'get-dsc-resource-kit' do
  code <<-EOH
    Archive reskit
    {
      ensure = 'Present'
      path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip"
      destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules"
    }
  EOH
end

where:

  • the remote_file resource is first used to download the DSCResourceKit620082014.zip file.

The full syntax for all of the properties that are available to the dsc_script resource is:

dsc_script 'name' do
  code                       String
  command                    String
  configuration_data         String
  configuration_data_script  String
  configuration_name         String
  cwd                        String
  environment                Hash
  flags                      Hash
  imports                    Array
  timeout                    Integer
  action                     Symbol # defaults to :run if not specified
end

where:

  • dsc_script is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • code, command, configuration_data, configuration_data_script, configuration_name, cwd, environment, flags, imports, and timeout are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The dsc_script resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:run
Default. Use to run the DSC configuration defined as defined in this resource.

Properties


The dsc_script resource has the following properties:

code
Ruby Type: String

The code for the DSC configuration script. This property may not be used in conjunction with the command property.

command
Ruby Type: String

The path to a valid Windows PowerShell data file that contains the DSC configuration script. This data file must be capable of running independently of Chef and must generate a valid DSC configuration. This property may not be used in conjunction with the code property.

configuration_data
Ruby Type: String

The configuration data for the DSC script. The configuration data must be a valid Windows PowerShell data file. This property may not be used in conjunction with the configuration_data_script property.

configuration_data_script
Ruby Type: String

The path to a valid Windows PowerShell data file that also contains a node called localhost. This property may not be used in conjunction with the configuration_data property.

configuration_name
Ruby Type: String

The name of a valid Windows PowerShell cmdlet. The name may only contain letter (a-z, A-Z), number (0-9), and underscore (_) characters and should start with a letter. The name may not be null or empty. This property may not be used in conjunction with the code property.

cwd
Ruby Type: String

The current working directory.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({'ENV_VARIABLE' => 'VALUE'}). (These variables must exist for a command to be run successfully.)

flags
Ruby Type: Hash

Pass parameters to the DSC script that is specified by the command property. Parameters are defined as key-value pairs, where the value of each key is the parameter to pass. This property may not be used in the same recipe as the code property. For example: flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' }).

imports
Ruby Type: Array

Warning

This property MUST be used with the code attribute.

Use to import DSC resources from a module.

To import all resources from a module, specify only the module name:

imports 'module_name'

To import specific resources, specify the module name, and then specify the name for each resource in that module to import:

imports 'module_name', 'resource_name_a', 'resource_name_b', ...

For example, to import all resources from a module named cRDPEnabled:

imports 'cRDPEnabled'

To import only the PSHOrg_cRDPEnabled resource:

imports 'cRDPEnabled', 'PSHOrg_cRDPEnabled'

timeout
Ruby Type: Integer

The amount of time (in seconds) a command is to wait before timing out.

ps_credential Helper

Use the ps_credential helper to embed a PSCredential object— a set of security credentials, such as a user name or password —within a script, which allows that script to be run using security credentials.

For example, assuming the CertificateID is configured in the local configuration manager, the SeaPower1@3 object is created and embedded within the seapower-user script:

dsc_script 'seapower-user' do
  code <<-EOH
    User AlbertAtom
    {
      UserName = 'AlbertAtom'
      Password = #{ps_credential('SeaPower1@3')}
    }
  EOH
  configuration_data <<-EOH
    @{
      AllNodes = @(
        @{
          NodeName = "localhost";
          CertificateID = 'A8D1234559F349F7EF19104678908F701D4167'
        }
      )
    }
  EOH
end

Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the dsc_script resource in recipes:

Specify DSC code directly

DSC data can be specified directly in a recipe:

dsc_script 'emacs' do
  code <<-EOH
  Environment 'texteditor'
  {
    Name = 'EDITOR'
    Value = 'c:\\emacs\\bin\\emacs.exe'
  }
  EOH
end

Specify DSC code using a Windows PowerShell data file

Use the command property to specify the path to a Windows PowerShell data file. For example, the following Windows PowerShell script defines the DefaultEditor:

Configuration 'DefaultEditor'
{
  Environment 'texteditor'
    {
      Name = 'EDITOR'
      Value = 'c:\emacs\bin\emacs.exe'
    }
}

Use the following recipe to specify the location of that data file:

dsc_script 'DefaultEditor' do
  command 'c:\dsc_scripts\emacs.ps1'
end

Pass parameters to DSC configurations

If a DSC script contains configuration data that takes parameters, those parameters may be passed using the flags property. For example, the following Windows PowerShell script takes parameters for the EditorChoice and EditorFlags settings:

$choices = @{'emacs' = 'c:\emacs\bin\emacs';'vi' = 'c:\vim\vim.exe';'powershell' = 'powershell_ise.exe'}
  Configuration 'DefaultEditor'
    {
      [CmdletBinding()]
      param
        (
          $EditorChoice,
          $EditorFlags = ''
        )
      Environment 'TextEditor'
      {
        Name = 'EDITOR'
        Value =  "$($choices[$EditorChoice]) $EditorFlags"
      }
    }

Use the following recipe to set those parameters:

dsc_script 'DefaultEditor' do
  flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' })
  command 'c:\dsc_scripts\editors.ps1'
end

Use custom configuration data

Configuration data in DSC scripts may be customized from a recipe. For example, scripts are typically customized to set the behavior for Windows PowerShell credential data types. Configuration data may be specified in one of three ways:

  • By using the configuration_data attribute
  • By using the configuration_data_script attribute
  • By specifying the path to a valid Windows PowerShell data file

The following example shows how to specify custom configuration data using the configuration_data property:

dsc_script 'BackupUser' do
  configuration_data <<-EOH
    @{
     AllNodes = @(
          @{
          NodeName = "localhost";
          PSDscAllowPlainTextPassword = $true
          })
     }
  EOH
  code <<-EOH
    $user = 'backup'
    $password = ConvertTo-SecureString -String "YourPass$(random)" -AsPlainText -Force
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $password

   User $user
     {
       UserName = $user
       Password = $cred
       Description = 'Backup operator'
       Ensure = "Present"
       Disabled = $false
       PasswordNeverExpires = $true
       PasswordChangeRequired = $false
     }
   EOH
end

The following example shows how to specify custom configuration data using the configuration_name property. For example, the following Windows PowerShell script defines the vi configuration:

Configuration 'emacs'
  {
    Environment 'TextEditor'
    {
      Name = 'EDITOR'
      Value = 'c:\emacs\bin\emacs.exe'
    }
}

Configuration 'vi'
{
    Environment 'TextEditor'
    {
      Name = 'EDITOR'
      Value = 'c:\vim\bin\vim.exe'
    }
}

Use the following recipe to specify that configuration:

dsc_script 'EDITOR' do
  configuration_name 'vi'
  command 'C:\dsc_scripts\editors.ps1'
end

Using DSC with other Chef resources

The dsc_script resource can be used with other resources. The following example shows how to download a file using the remote_file resource, and then uncompress it using the DSC Archive resource:

remote_file "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" do
  source 'http://gallery.technet.microsoft.com/DSC-Resource-Kit-All-c449312d/file/124481/1/DSC%20Resource%20Kit%20Wave%206%2008282014.zip'
end

dsc_script 'get-dsc-resource-kit' do
  code <<-EOH
    Archive reskit
    {
      ensure = 'Present'
      path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip"
      destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules"
    }
  EOH
end

execute resource

execute resource page

Use the execute resource to execute a single command. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Note

Use the script resource to execute a script using a specific interpreter (Ruby, Python, Perl, csh, or Bash).

Syntax


An execute resource block typically executes a single command that is unique to the environment in which a recipe will run. Some execute resource commands are run by themselves, but often they are run in combination with other Chef resources. For example, a single command that is run by itself:

execute 'apache_configtest' do
  command '/usr/sbin/apachectl configtest'
end

The full syntax for all of the properties that are available to the execute resource is:

execute 'name' do
  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
  group            String, Integer
  input            String
  live_stream      true, false # default value: false
  password         String
  returns          Integer, Array # default value: 0
  sensitive        true, false
  timeout          Integer, String, Float # default value: 3600
  umask            String, Integer
  user             String, Integer
  action           Symbol # defaults to :run if not specified
end

where:

  • execute is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • command, creates, cwd, default_env, domain, elevated, environment, group, input, live_stream, password, returns, sensitive, timeout, umask, and user are the properties available to this resource.

Actions


The execute resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:run
Default. Run a command.

Properties


The execute resource has the following properties:

command
Ruby Type: String, Array | Default Value: The resource block's name

The name of the command to be executed. Default value: the name of the resource block. See “Syntax” section above for more information.

Note

Use the execute resource to run a single command. Use multiple execute resource blocks to run multiple commands.

creates
Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd
Ruby Type: String

The current working directory from which 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 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.

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) 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.

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.

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.

sensitive
Ruby Type: true, false | Default Value: True if the password property is set. False otherwise.

Ensure that sensitive resource data is not logged by the Chef Infra Client.

timeout
Ruby Type: Integer, String, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

umask
Ruby Type: String, Integer

The file mode creation mask, or umask.

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. domainuser or user@my.dns.domain.com via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain 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 retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the execute resource in recipes:

Run a command upon notification:

execute 'slapadd' do
  command 'slapadd < /tmp/something.ldif'
  creates '/var/lib/slapd/uid.bdb'

  action :nothing
end

template '/tmp/something.ldif' do
  source 'something.ldif'

  notifies :run, 'execute[slapadd]', :immediately
end

Run a touch file only once while running a command:

execute 'upgrade script' do
  command 'php upgrade-application.php && touch /var/application/.upgraded'

  creates '/var/application/.upgraded'
  action :run
end

Run a command which requires an environment variable:

execute 'slapadd' do
  command 'slapadd < /tmp/something.ldif'
  creates '/var/lib/slapd/uid.bdb'

  action :run
  environment ({'HOME' => '/home/my_home'})
end

Delete a repository using yum to scrub the cache:

# the following code sample thanks to gaffneyc @ https://gist.github.com/918711
execute 'clean-yum-cache' do
  command 'yum clean all'
  action :nothing
end

file '/etc/yum.repos.d/bad.repo' do
  action :delete
  notifies :run, 'execute[clean-yum-cache]', :immediately
end

Prevent restart and reconfigure if configuration is broken:

Use the :nothing action (common to all resources) to prevent the test from starting automatically, and then use the subscribes notification to run a configuration test when a change to the template is detected.

execute 'test-nagios-config' do
  command 'nagios3 --verify-config'
  action :nothing
  subscribes :run, 'template[/etc/nagios3/configures-nagios.conf]', :immediately
end

Notify in a specific order:

To notify multiple resources, and then have these resources run in a certain order, do something like the following.

execute 'foo' do
  command '...'
  notifies :create, 'template[baz]', :immediately
  notifies :install, 'package[bar]', :immediately
  notifies :run, 'execute[final]', :immediately
end

template 'baz' do
  #...
  notifies :run, 'execute[restart_baz]', :immediately
end

package 'bar'
  execute 'restart_baz'
  execute 'final' do
  command '...'
end

where the sequencing will be in the same order as the resources are listed in the recipe: execute 'foo', template 'baz', execute [restart_baz], package 'bar', and execute 'final'.

Execute a command using a template:

The following example shows how to set up IPv4 packet forwarding using the execute resource to run a command named forward_ipv4 that uses a template defined by the template resource.

execute 'forward_ipv4' do
  command 'echo > /proc/.../ipv4/ip_forward'
  action :nothing
end

template '/etc/file_name.conf' do
  source 'routing/file_name.conf.erb'

 notifies :run, 'execute[forward_ipv4]', :delayed
end

where the command property for the execute resource contains the command that is to be run and the source property for the template resource specifies which template to use. The notifies property for the template specifies that the execute[forward_ipv4] (which is defined by the execute resource) should be queued up and run at the end of a Chef Infra Client run.

Add a rule to an IP table:

The following example shows how to add a rule named test_rule to an IP table using the execute resource to run a command using a template that is defined by the template resource:

execute 'test_rule' do
  command 'command_to_run
    --option value
    --option value
    --source #{node[:name_of_node][:ipsec][:local][:subnet]}
    -j test_rule'

  action :nothing
end

template '/etc/file_name.local' do
  source 'routing/file_name.local.erb'
  notifies :run, 'execute[test_rule]', :delayed
end

where the command property for the execute resource contains the command that is to be run and the source property for the template resource specifies which template to use. The notifies property for the template specifies that the execute[test_rule] (which is defined by the execute resource) should be queued up and run at the end of a Chef Infra Client run.

Stop a service, do stuff, and then restart it:

The following example shows how to use the execute, service, and mount resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following:

  • Checks to see if the Amazon EC2 node has MySQL
  • If the node has MySQL, stops MySQL
  • Installs MySQL
  • Mounts the node
  • Restarts MySQL
# the following code sample comes from the ``server_ec2``
# recipe in the following cookbook:
# https://github.com/chef-cookbooks/mysql

if (node.attribute?('ec2') && !FileTest.directory?(node['mysql']['ec2_path']))
  service 'mysql' do
    action :stop
  end

  execute 'install-mysql' do
    command "mv #{node['mysql']['data_dir']} #{node['mysql']['ec2_path']}"
    not_if { ::File.directory?(node['mysql']['ec2_path']) }
  end

  [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir|
    directory dir do
      owner 'mysql'
      group 'mysql'
    end
  end

  mount node['mysql']['data_dir'] do
    device node['mysql']['ec2_path']
    fstype 'none'
    options 'bind,rw'
    action [:mount, :enable]
  end

  service 'mysql' do
    action :start
  end
end

where

  • the two service resources are used to stop, and then restart the MySQL service
  • the execute resource is used to install MySQL
  • the mount resource is used to mount the node and enable MySQL

Use the platform_family? method:

The following is an example of using the platform_family? method in the Recipe DSL to create a variable that can be used with other resources in the same recipe. In this example, platform_family? is being used to ensure that a specific binary is used for a specific platform before using the remote_file resource to download a file from a remote location, and then using the execute resource to install that file by running a command.

if platform_family?('rhel')
  pip_binary = '/usr/bin/pip'
else
  pip_binary = '/usr/local/bin/pip'
end

remote_file "#{Chef::Config[:file_cache_path]}/distribute_setup.py" do
  source 'http://python-distribute.org/distribute_setup.py'
  mode '0755'
  not_if { ::File.exist?(pip_binary) }
end

execute 'install-pip' do
  cwd Chef::Config[:file_cache_path]
  command <<~EOF
    # command for installing Python goes here
  EOF
  not_if { ::File.exist?(pip_binary) }
end

where a command for installing Python might look something like:

#{node['python']['binary']} distribute_setup.py #{::File.dirname(pip_binary)}/easy_install pip

Control a service using the execute resource:

Warning

This is an example of something that should NOT be done. Use the **service** resource to control a service, not the **execute** resource.

Do something like this:

service 'tomcat' do
  action :start
end

and NOT something like this:

execute 'start-tomcat' do
  command '/etc/init.d/tomcat start'
  action :run
end

There is no reason to use the execute resource to control a service because the service resource exposes the start_command property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner.

Use the search recipe DSL method to find users:

The following example shows how to use the search method in the Recipe DSL to search for users:

#  the following code sample comes from the openvpn cookbook:

search("users", "*:*") do |u|
  execute "generate-openvpn-#{u['id']}" do
    command "./pkitool #{u['id']}"
    cwd '/etc/openvpn/easy-rsa'
  end

  %w{ conf ovpn }.each do |ext|
    template "#{node['openvpn']['key_dir']}/#{u['id']}.#{ext}" do
      source 'client.conf.erb'
      variables :username => u['id']
    end
  end
end

where

  • the search data will be used to create execute resources
  • the template resource tells Chef Infra Client which template to use

Enable remote login for macOS:

execute 'enable ssh' do
  command '/usr/sbin/systemsetup -setremotelogin on'
  not_if '/usr/sbin/systemsetup -getremotelogin | /usr/bin/grep On'
  action :run
end

Execute code immediately, based on the template resource:

By default, notifications are :delayed, that is they are queued up as they are triggered, and then executed at the very end of a Chef Infra Client run. To run kan 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

Sourcing a file:

The execute resource cannot be used to source a file (e.g. command 'source filename'). The following example will fail because source is not an executable:

execute 'foo' do
  command 'source /tmp/foo.sh'
end

Instead, use the script resource or one of the script-based resources (bash, csh, perl, python, or ruby). For example:

bash 'foo' do
  code 'source /tmp/foo.sh'
end

Run a Knife command:

execute 'create_user' do
  command <<~EOM
    knife user create #{user}
      --admin
      --password password
      --disable-editing
      --file /home/vagrant/.chef/user.pem
      --config /tmp/knife-admin.rb
    EOM
end

Run install command into virtual environment:

The following example shows how to install a lightweight JavaScript framework into Vagrant:

execute "install q and zombiejs" do
  cwd "/home/vagrant"
  user "vagrant"
  environment ({'HOME' => '/home/vagrant', 'USER' => 'vagrant'})
  command "npm install -g q zombie should mocha coffee-script"
  action :run
end

Run a command as a named user:

The following example shows how to run bundle install from a Chef Infra Client run as a specific user. This will put the gem into the path of the user (vagrant) instead of the root user (under which the Chef Infra Client runs):

execute '/opt/chefdk/embedded/bin/bundle install' do
  cwd node['chef_workstation']['bundler_path']
  user node['chef_workstation']['user']

  environment ({
    'HOME' => "/home/#{node['chef_workstation']['user']}",
    'USER' => node['chef_workstation']['user']
  })
  not_if 'bundle check'
end

Run a command as an alternate user:

Note: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator.

This right can be added and checked in a recipe using this example:

# Add 'SeAssignPrimaryTokenPrivilege' for the user
Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege')

# Check if the user has 'SeAssignPrimaryTokenPrivilege' rights
Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege')

The following example shows how to run mkdir test_dir from a Chef Infra Client run as an alternate user.

# Passing only username and password
execute 'mkdir test_dir' do
  cwd Chef::Config[:file_cache_path]

  user "username"
  password "password"
end

# Passing username and domain
execute 'mkdir test_dir' do
  cwd Chef::Config[:file_cache_path]

  domain "domain-name"
  user "user"
  password "password"
end

# Passing username = 'domain-name\username'. No domain is passed
execute 'mkdir test_dir' do
  cwd Chef::Config[:file_cache_path]

  user "domain-name\username"
  password "password"
end

# Passing username = 'username@domain-name'.  No domain is passed
execute 'mkdir test_dir' do
  cwd Chef::Config[:file_cache_path]

  user "username@domain-name"
  password "password"
end

Run a command with an external input file:

execute ‘md5sum’ do input File.read(FILE) end

file resource

file resource page

Use the file resource to manage files directly on a node.

Note

Use the cookbook_file resource to copy a file from a cookbook’s /files directory. Use the template resource to create a file based on a template in a cookbook’s /templates directory. And use the remote_file resource to transfer a file to a node from a remote location.

Syntax


A file resource block manages files that exist on nodes. For example, to write the home page for an Apache website:

file '/var/www/customers/public_html/index.php' do
  content '<html>This is a placeholder for the home page.</html>'
  mode '0755'
  owner 'web_admin'
  group 'web_admin'
end

where:

  • '/var/www/customers/public_html/index.php' is path to the file and also the filename to be managed
  • content defines the contents of the file

The full syntax for all of the properties that are available to the file resource is:

file 'name' do
  atomic_update              true, false
  backup                     false, Integer
  checksum                   String
  content                    String
  force_unlink               true, false
  group                      String, Integer
  inherits                   true, false
  manage_symlink_source      true, false
  mode                       String, Integer
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  rights                     Hash
  verify                     String, Block
  action                     Symbol # defaults to :create if not specified
end

where:

  • file is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • atomic_update, backup, checksum, content, force_unlink, group, inherits, manage_symlink_source, mode, owner, path, rights, sensitive, and verify are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The file resource has the following actions:

:create
Default. Create a file. If a file already exists (but does not match), update that file to match.
:create_if_missing
Create a file only if the file does not exist. When the file exists, nothing happens.
:delete
Delete a file.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:touch
Touch a file. This updates the access (atime) and file modification (mtime) times for a file.

Properties


The file resource has the following properties:

atomic_update
Ruby Type: true, false

Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides file_atomic_update, which is a global setting found in the client.rb file.

backup
Ruby Type: Integer, false | Default Value: 5

The number of backups to be kept in /var/chef/backup (for UNIX- and Linux-based platforms) or C:/chef/backup (for the Microsoft Windows platform). Set to false to prevent backups from being kept.

checksum
Ruby Type: String

The SHA-256 checksum of the file. Use to ensure that a specific file is used. If the checksum does not match, the file is not used. Default value: no checksum required.

content
Ruby Type: String

A string that is written to the file. The contents of this property replace any previous content when this property has something other than the default value. The default behavior will not modify content.

force_unlink
Ruby Type: true, false | Default Value: false

How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to true for Chef Infra Client delete the non-file target and replace it with the specified file. Set to false for Chef Infra Client to raise an error.

group
Ruby Type: Integer, String

A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

inherits
Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

manage_symlink_source
Ruby Type: true, false | Default Value: true

(with warning)

Change the behavior of the file resource if it is pointed at a symlink. When this value is set to false, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to true, Chef will follow the symlink and will manage the permissions and content of symlink’s target file.

The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning.

mode
Ruby Type: Integer, String

A quoted 3-5 character string that defines the octal mode. For example: '755', '0755', or 00755. If mode is not specified and if the file already exists, the existing mode on the file is used. If mode is not specified, the file does not exist, and the :create action is specified, Chef Infra Client assumes a mask value of '0777' and then applies the umask for the system on which the file is to be created to the mask value. For example, if the umask on a system is '022', Chef Infra Client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

owner
Ruby Type: Integer, String

A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path
Ruby Type: String

The full path to the file, including the file name and its extension. For example: /files/file.txt. Default value: the name of the resource block. See “Syntax” section above for more information.

Microsoft Windows: A path that begins with a forward slash (/) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended.

rights
Ruby Type: Integer, String

Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options.

verify
Ruby Type: String, Block

Allows verification of a file’s contents before it is created. Creates a temporary file and then allows execution of commands or Ruby code. If this code evaluates to true, the file is created. If the code evaluates to false, an error is raised.

The types for this property are a block or a string. When specified as a block, it returns true or false. When specified as a string, it is executed as a system command. It evaluates to true if the command returns 0 as its exit status code and false if the command returns a non-zero exit status code.

Note

A block is arbitrary Ruby defined within the resource block by using the verify property. When a block returns true, Chef Infra Client will continue to update the file as appropriate.

For example, this should return true:

file '/tmp/baz' do
  verify { 1 == 1 }
end

This should also return true:

file '/etc/nginx.conf' do
  verify 'nginx -t -c %{path}'
end

In this example, the %{path} portion of this command is expanded to the temporary location where a copy of the file to be created exists. This will use Nginx’s syntax checking feature to ensure the file is a valid Nginx configuration file before writing the file. An error will be raised if the executed command returns a non-zero exit status code.

This should return true:

file '/tmp/foo' do
  content "hello"
  verify do |path|
    open(path).read.include? "hello"
  end
end

Whereas, this should return false:

file '/tmp/foo' do
  content "goodbye"
  verify do |path|
    open(path).read.include? "hello"
  end
end

If a string or a block return false, the Chef Infra Client run will stop and an error is raised.

Atomic File Updates

Atomic updates are used with file-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out.

Atomic updates are enabled by default. They can be managed globally using the file_atomic_update setting in the client.rb file. They can be managed on a per-resource basis using the atomic_update property that is available with the cookbook_file, file, remote_file, and template resources.

Note

On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the restorecon command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected.

Windows File Security

To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes. Access Control Lists (ACLs)

The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the rights property is as follows:

rights permission, principal, option_type => value

where

permission

Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control.

These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read.

(For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.)

principal

Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the SDDL string constants. Chef Infra Client does not need to know if a principal is a user or a group.

option_type

A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types:

Option TypeDescription
:applies_to_childrenSpecify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).
:applies_to_selfIndicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.
:one_level_deepIndicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, 'S-1-1-0'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
end

or:

rights :read, ['Administrators','Everyone']
rights :full_control, 'Users', :applies_to_children => true
rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true

Some other important things to know when using the rights attribute:

  • Only inherited rights remain. All existing explicit rights on the object are removed and replaced.
  • If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified.
  • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration.

Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
  deny_rights :read, ['Julian', 'Lewis']
end

or:

deny_rights :full_control, ['Sally']
Inheritance

By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The inherits property can be used to specifically tell Chef Infra Client to apply (or not apply) inherited rights from its parent directory.

For example, the following example specifies the rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
end

and then the following example specifies how to use inheritance to deny access to the child directory:

directory 'C:\mordor\mount_doom' do
  rights :full_control, 'MORDOR\Sauron'
  inherits false # Sauron is the only person who should have any sort of access
end

If the deny_rights permission were to be used instead, something could slip through unless all users and groups were denied.

Another example also shows how to specify rights for a directory:

directory 'C:\mordor' do
  rights :read, 'MORDOR\Minions'
  rights :full_control, 'MORDOR\Sauron'
  rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there
end

but then not use the inherits property to deny those rights on a child directory:

directory 'C:\mordor\mount_doom' do
  deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough
end

Because the inherits property is not specified, Chef Infra Client will default it to true, which will ensure that security settings for existing files remain unchanged.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the file resource in recipes:

Create a file

file '/tmp/something' do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

Create a file in Microsoft Windows

To create a file in Microsoft Windows, be sure to add an escape character—\—before the backslashes in the paths:

file 'C:\\tmp\\something.txt' do
  rights :read, 'Everyone'
  rights :full_control, 'DOMAIN\\User'
  action :create
end

Remove a file

file '/tmp/something' do
  action :delete
end

Set file modes

file '/tmp/something' do
  mode '0755'
end

Delete a repository using yum to scrub the cache

# the following code sample thanks to gaffneyc @ https://gist.github.com/918711

execute 'clean-yum-cache' do
  command 'yum clean all'
  action :nothing
end

file '/etc/yum.repos.d/bad.repo' do
  action :delete
  notifies :run, 'execute[clean-yum-cache]', :immediately
  notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately
end

Add the value of a data bag item to a file

The following example shows how to get the contents of a data bag item named impossible_things, create a .pem file located at some/directory/path/, and then use the content attribute to update the contents of that file with the value of the impossible_things data bag item:

private_key = data_bag_item('impossible_things', private_key_name)['private_key']

file "some/directory/path/#{private_key_name}.pem" do
  content private_key
  owner 'root'
  group 'group'
  mode '0755'
end

Write a YAML file

The following example shows how to use the content property to write a YAML file:

file "#{app['deploy_to']}/shared/config/settings.yml" do
  owner "app['owner']"
  group "app['group']"
  mode '0755'
  content app.to_yaml
end

Write a string to a file

The following example specifies a directory, and then uses the content property to add a string to the file created in that directory:

status_file = '/path/to/file/status_file'

file status_file do
  owner 'root'
  group 'root'
  mode '0755'
  content 'My favourite foremost coastal Antarctic shelf, oh Larsen B!'
end

Create a file from a copy

The following example shows how to copy a file from one directory to another, locally on a node:

file '/root/1.txt' do
  content IO.read('/tmp/1.txt')
  action :create
end

where the content attribute uses the Ruby IO.read method to get the contents of the /tmp/1.txt file.

freebsd_package resource

freebsd_package resource page

Use the freebsd_package resource to manage packages for the FreeBSD platform.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, 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


A freebsd_package resource block manages a package on a node, typically by installing it. The simplest use of the freebsd_package resource is:

freebsd_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the freebsd_package resource is:

freebsd_package 'name' do
  options           String
  package_name      String
  source            String
  timeout           String, Integer
  version           String
  action            Symbol # defaults to :install if not specified
end

where:

  • freebsd_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 freebsd_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
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 package.

Properties


The freebsd_package resource has the following properties:

options
Ruby Type: String

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

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the freebsd_package resource in recipes:

Install a package

freebsd_package 'name of package' do
  action :install
end

git resource

git resource page

Use the git resource to manage source control resources that exist in a git repository. git version 1.6.5 (or higher) is required to use all of the functionality in the git resource.

Syntax


A git resource block manages source control resources that exist in a git repository:

git "#{Chef::Config[:file_cache_path]}/app_name" do
  repository node[:app_name][:git_repository]
  revision node[:app_name][:git_revision]
  action :sync
end

The full syntax for all of the properties that are available to the git resource is:

git 'name' do
  additional_remotes      Hash
  checkout_branch         String # default value: "deploy"
  depth                   Integer
  destination             String # default value: 'name' unless specified
  enable_checkout         true, false # default value: true
  enable_submodules       true, false # default value: false
  environment             Hash
  group                   String, Integer
  remote                  String # default value: "origin"
  repository              String
  revision                String # default value: "HEAD"
  ssh_wrapper             String
  timeout                 Integer
  user                    String, Integer
  action                  Symbol # defaults to :sync if not specified
end

where:

  • git is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • additional_remotes, checkout_branch, depth, destination, enable_checkout, enable_submodules, environment, group, remote, repository, revision, ssh_wrapper, timeout, and user are the properties available to this resource.

Actions


The git resource has the following actions:

:checkout
Clone or check out the source. When a checkout is available, this provider does nothing.
:export
Export the source, excluding or removing any version control artifacts.
:nothing
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.
:sync
Default. Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes.

Properties


The git resource has the following properties:

additional_remotes
Ruby Type: Hash

A Hash of additional remotes that are added to the git repository configuration.

checkout_branch
Ruby Type: String | Default Value: deploy

Do a one-time checkout from git or use when a branch in the upstream repository is named deploy. To prevent the git resource from attempting to check out master from master, set enable_checkout to false when using the checkout_branch property. See revision.

depth
Ruby Type: Integer

The number of past revisions to be included in the git shallow clone. Unless specified the default behavior will do a full clone.

destination
Ruby Type: String | Default Value: The resource block's name

The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block.

enable_checkout
Ruby Type: true, false | Default Value: true

Check out a repo from master. Set to false when using the checkout_branch attribute to prevent the git resource from attempting to check out master from master.

enable_submodules
Ruby Type: true, false | Default Value: false

Perform a sub-module initialization and update.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

Note

The git provider automatically sets the ENV['HOME'] and ENV['GIT_SSH'] environment variables. To override this behavior and provide different values, add ENV['HOME'] and/or ENV['GIT_SSH'] to the environment Hash.

group
Ruby Type: String, Integer

The system group that is responsible for the checked-out code.

remote
Ruby Type: String | Default Value: "origin"

The remote repository to use when synchronizing an existing clone.

repository
Ruby Type: String

The URI for the git repository.

revision
Ruby Type: String | Default Value: HEAD

A branch, tag, or commit to be synchronized with git. This can be symbolic, like HEAD or it can be a source control management-specific revision identifier. See checkout_branch.

The value of the revision attribute may change over time. From one branch to another, to a tag, to a specific SHA for a commit, and then back to a branch. The revision attribute may even be changed in a way where history gets rewritten.

Instead of tracking a specific branch or doing a headless checkout, Chef Infra Client maintains its own branch (via the git resource) that does not exist in the upstream repository. Chef Infra Client is then free to forcibly check out this branch to any commit without destroying the local history of an existing branch.

For example, to explicitly track an upstream repository’s master branch:

revision 'master'

Use the git rev-parse and git ls-remote commands to verify that Chef Infra Client is synchronizing commits correctly. (Chef Infra Client always runs git ls-remote on the upstream repository to verify the commit is made to the correct repository.)

ssh_wrapper
Ruby Type: String

The path to the wrapper script used when running SSH with git. The GIT_SSH environment variable is set to this.

timeout
Ruby Type: Integer

The amount of time (in seconds) to wait for a command to execute before timing out. When this property is specified using the deploy resource, the value of the timeout property is passed from the deploy resource to the git resource.

user
Ruby Type: String, Integer

The system user that is responsible for the checked-out code. Default value: the home directory of this user, as indicated by the HOME environment variable.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the git resource in recipes:

Use the git mirror

git '/opt/mysources/couch' do
  repository 'git://git.apache.org/couchdb.git'
  revision 'master'
  action :sync
end

Use different branches

To use different branches, depending on the environment of the node:

if node.chef_environment == 'QA'
   branch_name = 'staging'
else
   branch_name = 'master'
end

git '/home/user/deployment' do
   repository 'git@github.com:gitsite/deployment.git'
   revision branch_name
   action :sync
   user 'user'
   group 'test'
end

where the branch_name variable is set to staging or master, depending on the environment of the node. Once this is determined, the branch_name variable is used to set the revision for the repository. If the git status command is used after running the example above, it will return the branch name as deploy, as this is the default value. Run Chef Infra Client in debug mode to verify that the correct branches are being checked out:

sudo chef-client -l debug

Install an application from git using bash

The following example shows how Bash can be used to install a plug-in for rbenv named ruby-build, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which ruby-build is located, and then runs a command.

git "#{Chef::Config[:file_cache_path]}/ruby-build" do
  repository 'git://github.com/sstephenson/ruby-build.git'
  revision 'master'
  action :sync
end

bash 'install_ruby_build' do
  cwd "#{Chef::Config[:file_cache_path]}/ruby-build"
  user 'rbenv'
  group 'rbenv'
  code <<-EOH
    ./install.sh
    EOH
  environment 'PREFIX' => '/usr/local'
end

To read more about ruby-build, see here: https://github.com/sstephenson/ruby-build.

Upgrade packages from git

The following example uses the git resource to upgrade packages:

# the following code sample comes from the ``source`` recipe
# in the ``libvpx-cookbook`` cookbook:
# https://github.com/enmasse-entertainment/libvpx-cookbook

git "#{Chef::Config[:file_cache_path]}/libvpx" do
  repository node[:libvpx][:git_repository]
  revision node[:libvpx][:git_revision]
  action :sync
  notifies :run, 'bash[compile_libvpx]', :immediately
end

Pass in environment variables

git '/opt/mysources/couch' do
  repository 'git://git.apache.org/couchdb.git'
  revision 'master'
  environment 'VAR' => 'whatever'
  action :sync
end

group resource

group resource page

Use the group resource to manage a local group.

Syntax


The group resource has the following syntax:

group 'name' do
  append                true, false # default value: false
  comment               String
  excluded_members      String, Array
  gid                   String, Integer
  group_name            String # default value: 'name' unless specified
  members               String, Array
  non_unique            true, false # default value: false
  system                true, false # default value: false
  action                Symbol # defaults to :create if not specified
end

where:

  • group is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • append, comment, excluded_members, gid, group_name, members, non_unique, and system are the properties available to this resource.

Actions


The group resource has the following actions:

:create
Default. Create a group. If a group already exists (but does not match), update that group to match.
:manage
Manage an existing group. This action does nothing if the group does not exist.
:modify
Modify an existing group. This action raises an exception if the group does not exist.
:nothing
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 group.

Properties


The group resource has the following properties:

append
Ruby Type: true, false | Default Value: false

How members should be appended and/or removed from a group. When true, members are appended and excluded_members are removed. When false, group members are reset to the value of the members property.

comment
Ruby Type: String

Specifies a comment to associate with the local group.

New in Chef Client 14.9

excluded_members
Ruby Type: String, Array

Remove users from a group. May only be used when append is set to true.

gid
Ruby Type: String, Integer

The identifier for the group.

group_name
Ruby Type: String | Default Value: The resource block's name

The name of the group. Default value: the name of the resource block. See “Syntax” section above for more information.

members
Ruby Type: Array

Which users should be set or appended to a group. When more than one group member is identified, the list of members should be an array: members ['user1', 'user2'].

non_unique
Ruby Type: true, false | Default Value: false

Allow gid duplication. May only be used with the Groupadd provider.

system
Ruby Type: true, false | Default Value: false

Set if a group belongs to a system group. Set to true if the group belongs to a system group.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the group resource in recipes:

Append users to groups

group 'www-data' do
  action :modify
  members 'maintenance'
  append true
end

Add a user to group on the Windows platform

group 'Administrators' do
  members ['domain\foo']
  append true
  action :modify
end

homebrew_cask resource

homebrew_cask resource page

Use the homebrew_cask resource to install binaries distributed via the Homebrew package manager.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the homebrew_cask resource is:

homebrew_cask 'name' do
  cask_name          String # default value: 'name' unless specified
  homebrew_path      String # default value: "/usr/local/bin/brew"
  install_cask       true, false # default value: true
  options            String
  owner              String, Integer
  action             Symbol # defaults to :install if not specified
end

where:

  • homebrew_cask is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • cask_name, homebrew_path, install_cask, options, and owner are the properties available to this resource.

Actions


The homebrew_cask resource has the following actions:

:install
Default. Install an application that is packaged as a Homebrew cask.
: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 an application that is packaged as a Homebrew cask.

Properties


The homebrew_cask resource has the following properties:

cask_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the cask name if it differs from the resource block’s name.

homebrew_path
Ruby Type: String | Default Value: /usr/local/bin/brew

The path to the homebrew binary.

install_cask
Ruby Type: true, false | Default Value: true

Automatically install the Homebrew cask tap, if necessary.

options
Ruby Type: String

Options to pass to the brew command during installation.

owner
Ruby Type: String, Integer | Default Value: lazy default

The owner of the Homebrew installation.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

homebrew_package resource

homebrew_package resource page

Use the homebrew_package resource to manage packages for the macOS platform.

Note

Starting with Chef Infra Client 16 the homebrew resource now accepts an array of packages for installing multiple packages at once.

New in Chef Infra Client 12.0.

Syntax


The full syntax for all of the properties that are available to the homebrew_package resource is:

homebrew_package 'name' do
  homebrew_user      String, Integer
  options            String, Array
  package_name       String, Array
  source             String
  timeout            String, Integer
  version            String, Array
  action             Symbol # defaults to :install if not specified
end

where:

  • homebrew_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.
  • homebrew_user, options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The homebrew_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.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The homebrew_package resource has the following properties:

homebrew_user
Ruby Type: String, Integer

The name or uid of the Homebrew owner to be used by Chef Infra Client when executing a command.

Chef Infra Client, by default, will attempt to execute a Homebrew command as the owner of /usr/local/bin/brew. If that executable does not exist, Chef Infra Client will attempt to find the user by executing which brew. If that executable cannot be found, Chef Infra Client will print an error message: Could not find the "brew" executable in /usr/local/bin or anywhere on the path.. Use the homebrew_user attribute to specify the Homebrew owner for situations where Chef Infra Client cannot automatically detect the correct owner.

options
Ruby Type: String, Array

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to:

  • Download the specified packages and versions via a single HTTP transaction
  • Update or install multiple packages with a single resource during a Chef Infra Client run

For example, installing multiple packages:

package %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(package1 package2)  do
  action :nothing
end

log 'call a notification' do
  notifies :install, 'package[package1, package2]', :immediately
end

Note

Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the package_name or version properties.

Examples


The following examples demonstrate various approaches for using the homebrew_package resource in recipes:

Install a package:

homebrew_package 'git'

Install multiple packages at once:

homebrew_package %w(git fish ruby)

Specify the Homebrew user with a UUID

homebrew_package 'git' do
  homebrew_user 1001
end

Specify the Homebrew user with a string:

homebrew_package 'vim' do
  homebrew_user 'user1'
end

homebrew_tap resource

homebrew_tap resource page

Use the homebrew_tap resource to add additional formula repositories to the Homebrew package manager.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the homebrew_tap resource is:

homebrew_tap 'name' do
  full               true, false # default value: false
  homebrew_path      String # default value: "/usr/local/bin/brew"
  owner              String
  tap_name           String # default value: 'name' unless specified
  url                String
  action             Symbol # defaults to :tap if not specified
end

where:

  • homebrew_tap is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • full, homebrew_path, owner, tap_name, and url are the properties available to this resource.

Actions


The homebrew_tap resource has the following actions:

: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.
:tap
Default. Add a Homebrew tap.
:untap
Remove a Homebrew tap.

Properties


The homebrew_tap resource has the following properties:

full
Ruby Type: true, false | Default Value: false

Perform a full clone on the tap, as opposed to a shallow clone.

homebrew_path
Ruby Type: String | Default Value: /usr/local/bin/brew

The path to the Homebrew binary.

owner
Ruby Type: String | Default Value: Calculated default username

The owner of the Homebrew installation.

tap_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the tap name if it differs from the resource block’s name.

url
Ruby Type: String

The URL of the tap.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

homebrew_update resource

homebrew_update resource page

Use the homebrew_update resource to manage Homebrew repository updates on macOS.

New in Chef Infra Client 16.2.

Syntax


The full syntax for all of the properties that are available to the homebrew_update resource is:

homebrew_update 'name' do
  frequency      Integer # default value: 86400
  action         Symbol # defaults to :periodic if not specified
end

where:

  • homebrew_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.

Actions


The homebrew_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
Run a periodic update based on the frequency property
:update
Run an immediate update

Properties


The homebrew_update resource has the following properties:

frequency
Ruby Type: Integer | Default Value: 86400

Determines how frequently (in seconds) Homebrew updates are made. Use this property when the :periodic action is specified.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the homebrew_update resource in recipes:

Update the homebrew repository data at a specified interval:

homebrew_update 'all platforms' do
  frequency 86400
  action :periodic
end

Update the Homebrew repository at the start of a Chef Infra Client run:

homebrew_update 'update'

hostname resource

hostname resource page

Use the hostname resource to set the system’s hostname, configure hostname and hosts config file, and re-run the Ohai hostname plugin so the hostname will be available in subsequent cookbooks.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the hostname resource is:

hostname 'name' do
  aliases             Array
  compile_time        true, false # default value: true
  hostname            String # default value: 'name' unless specified
  ipaddress           String # default value: The node's IP address as determined by Ohai.
  windows_reboot      true, false # default value: true
  action              Symbol # defaults to :set if not specified
end

where:

  • hostname is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • aliases, compile_time, hostname, ipaddress, and windows_reboot are the properties available to this resource.

Actions


The hostname resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:set
Default action. Set the node’s hostname.

Properties


The hostname resource has the following properties:

aliases
Ruby Type: Array

An array of hostname aliases to use when configuring the hosts file.

compile_time
Ruby Type: true, false | Default Value: true

Determines whether or not the resource should be run at compile time.

hostname
Ruby Type: String | Default Value: The resource block's name

An optional property to set the hostname if it differs from the resource block’s name.

ipaddress
Ruby Type: String | Default Value: The node's IP address as determined by Ohai.

The IP address to use when configuring the hosts file.

windows_reboot
Ruby Type: true, false | Default Value: true

Determines whether or not Windows should be reboot after changing the hostname, as this is required for the change to take effect.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the hostname resource in recipes:

Set the hostname using the IP address, as detected by Ohai:

hostname 'example'

Manually specify the hostname and IP address:

hostname 'statically_configured_host' do
  hostname 'example'
  ipaddress '198.51.100.2'
end

http_request resource

http_request resource page

Use the http_request resource to send an HTTP request (GET, PUT, POST, DELETE, HEAD, or OPTIONS) with an arbitrary message. This resource is often useful when custom callbacks are necessary.

Syntax


A http_request resource block sends HTTP requests with an arbitrary message. For example, send a DELETE request to 'http://www.chef.io/some_page?message=please_delete_me'.

http_request 'please_delete_me' do
  url 'http://www.chef.io/some_page'
  action :delete
end

The full syntax for all of the properties that are available to the http_request resource is:

http_request 'name' do
  headers                    Hash
  message                    Object # defaults to 'name' if not specified
  url                        String
  action                     Symbol # defaults to :get if not specified
end

where:

  • http_request is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • headers, message, and url are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The http_request resource has the following actions:

:delete
Send a DELETE request.
:get
Default. Send a GET request. Changed in Chef Client 12.0 to deprecate the hard-coded query string from earlier versions. Cookbooks that rely on this string need to be updated to manually add it to the URL as it is passed to the resource.
:head
Send a HEAD request.
:nothing
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.
:options
Send an OPTIONS request.
:post
Send a POST request.
:put
Send a PUT request.

Properties


The http_request resource has the following properties:

headers
Ruby Type: Hash

A Hash of custom headers.

message
Ruby Type: Object

The message that is sent by the HTTP request. Default value: the name of the resource block. See “Syntax” section above for more information.

url
Ruby Type: String

The URL to which an HTTP request is sent.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the http_request resource in recipes:

Send a GET request

http_request 'some_message' do
  url 'http://example.com/check_in'
end

The message is sent as http://example.com/check_in?message=some_message.

Send a POST request

To send a POST request as JSON data, convert the message to JSON and include the correct content-type header. For example:

http_request 'posting data' do
  action :post
  url 'http://example.com/check_in'
  message ({:some => 'data'}.to_json)
  headers({'AUTHORIZATION' => "Basic #{
    Base64.encode64('username:password')}",
    'Content-Type' => 'application/data'
  })
end

Transfer a file only when the remote source changes

remote_file '/tmp/couch.png' do
  source 'http://couchdb.apache.org/img/sketch.png'
  action :nothing
end

http_request 'HEAD http://couchdb.apache.org/img/sketch.png' do
  message ''
  url 'http://couchdb.apache.org/img/sketch.png'
  action :head
  if ::File.exist?('/tmp/couch.png')
    headers 'If-Modified-Since' => File.mtime('/tmp/couch.png').httpdate
  end
  notifies :create, 'remote_file[/tmp/couch.png]', :immediately
end

ifconfig resource

ifconfig resource page

Use the ifconfig resource to manage interfaces on Unix and Linux systems.

Syntax


The full syntax for all of the properties that are available to the ifconfig resource is:

ifconfig 'name' do
  bcast             String
  bonding_opts      String
  bootproto         String
  device            String
  ethtool_opts      String
  family            String # default value: "inet"
  gateway           String
  hwaddr            String
  inet_addr         String
  mask              String
  master            String
  metric            String
  mtu               String
  network           String
  onboot            String
  onparent          String
  slave             String
  target            String # default value: 'name' unless specified
  vlan              String
  action            Symbol # defaults to :add if not specified
end

where:

  • ifconfig is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • bcast, bonding_opts, bootproto, device, ethtool_opts, family, gateway, hwaddr, inet_addr, mask, master, metric, mtu, network, onboot, onparent, slave, target, and vlan are the properties available to this resource.

Actions


The ifconfig resource has the following actions:

:add
Default. Run ifconfig to configure a network interface and (on some platforms) write a configuration file for that network interface.
:delete
Run ifconfig to disable a network interface and (on some platforms) delete that network interface’s configuration file.
:disable
Run ifconfig to disable a network interface.
:enable
Run ifconfig to enable a network interface.
:nothing
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 ifconfig resource has the following properties:

bcast
Ruby Type: String

The broadcast address for a network interface. On some platforms this property is not set using ifconfig, but instead is added to the startup configuration file for the network interface.

bonding_opts
Ruby Type: String

Bonding options to pass via BONDING_OPTS on RHEL and CentOS. For example: mode=active-backup miimon=100.

New in Chef Client 13.4

bootproto
Ruby Type: String

The boot protocol used by a network interface.

device
Ruby Type: String

The network interface to be configured.

ethtool_opts
Ruby Type: String

Options to be passed to ethtool(8). For example: -A eth0 autoneg off rx off tx off.

New in Chef Client 13.4

family
Ruby Type: String | Default Value: inet

Networking family option for Debian-based systems; for example: inet or inet6.

New in Chef Client 14.0

gateway
Ruby Type: String

The gateway to use for the interface.

New in Chef Client 14.4

hwaddr
Ruby Type: String

The hardware address for the network interface.

inet_addr
Ruby Type: String

The Internet host address for the network interface.

mask
Ruby Type: String

The decimal representation of the network mask. For example: 255.255.255.0.

master
Ruby Type: String

Specifies the channel bonding interface to which the Ethernet interface is linked.

New in Chef Client 13.4

metric
Ruby Type: String

The routing metric for the interface.

mtu
Ruby Type: String

The maximum transmission unit (MTU) for the network interface.

network
Ruby Type: String

The address for the network interface.

onboot
Ruby Type: String

Bring up the network interface on boot.

onparent
Ruby Type: String

Bring up the network interface when its parent interface is brought up.

slave
Ruby Type: String

When set to yes, this device is controlled by the channel bonding interface that is specified via the master property.

New in Chef Client 13.4

target
Ruby Type: String | Default Value: The resource block's name

The IP address that is to be assigned to the network interface. If not specified we’ll use the resource’s name.

vlan
Ruby Type: String

The VLAN to assign the interface to.

New in Chef Client 14.4


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the ifconfig resource in recipes:

Configure a network interface

ifconfig "33.33.33.80" do
  bootproto "dhcp"
  device "eth1"
end

will create the following interface:

vagrant@default-ubuntu-2004:~cat /etc/network/interfaces.d/ifcfg-eth1
iface eth1 inet dhcp

Specify a boot protocol

ifconfig '192.186.0.1' do
  device 'eth0'
end

Specify a static IP address

ifconfig "33.33.33.80" do
  device "eth1"
end

will create the following interface:

iface eth1 inet static
  address 33.33.33.80

Update a static IP address with a boot protocol

ifconfig "33.33.33.80" do
  bootproto "dhcp"
  device "eth1"
end

will update the interface from static to dhcp:

iface eth1 inet dhcp
  address 33.33.33.80

ips_package resource

ips_package resource page

Use the ips_package resource to manage packages (using Image Packaging System (IPS)) on the Solaris 11 platform.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, 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


A ips_package resource block manages a package on a node, typically by installing it. The simplest use of the ips_package resource is:

ips_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the ips_package resource is:

ips_package 'name' do
  accept_license             true, false # default value: false
  options                    String
  package_name               String, Array
  source                     String
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • ips_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • accept_license, options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The ips_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
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 package.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The ips_package resource has the following properties:

accept_license
Ruby Type: true, false | Default Value: false

Accept an end-user license agreement, automatically.

options
Ruby Type: String

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the ips_package resource in recipes:

Install a package

ips_package 'name of package' do
  action :install
end

kernel_module resource

kernel_module resource page

Use the kernel_module resource to manage kernel modules on Linux systems. This resource can load, unload, blacklist, disable, install, and uninstall modules.

New in Chef Infra Client 14.3.

Syntax


The full syntax for all of the properties that are available to the kernel_module resource is:

kernel_module 'name' do
  load_dir        String # default value: "/etc/modules-load.d"
  modname         String # default value: 'name' unless specified
  options         Array
  unload_dir      String # default value: "/etc/modprobe.d"
  action          Symbol # defaults to :install if not specified
end

where:

  • kernel_module is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • load_dir, modname, options, and unload_dir are the properties available to this resource.

Actions


The kernel_module resource has the following actions:

:blacklist
Blacklist a kernel module.
:disable

Disable a kernel module

New in Chef Client 15.2.

:install
Default. Load kernel module, and ensure it loads on reboot.
:load
Load a kernel module.
: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
Unload a kernel module and remove module config, so it doesn’t load on reboot.
:unload
Unload kernel module.

Properties


The kernel_module resource has the following properties:

load_dir
Ruby Type: String | Default Value: /etc/modules-load.d

The directory to load modules from.

modname
Ruby Type: String | Default Value: The resource block's name

An optional property to set the kernel module name if it differs from the resource block’s name.

options
Ruby Type: Array

An optional property to set options for the kernel module.

New in Chef Infra Client 15.4

unload_dir
Ruby Type: String | Default Value: /etc/modprobe.d

The modprobe.d directory.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the kernel_module resource in recipes:

Install and load a kernel module, and ensure it loads on reboot.

kernel_module 'loop'

Install and load a kernel with a specific set of options, and ensure it loads on reboot. Consult kernel module documentation for specific options that are supported.

kernel_module 'loop' do
  options [
    'max_loop=4',
    'max_part=8'
  ]
end

Load a kernel module.

kernel_module 'loop' do
  action :load
end

Unload a kernel module and remove module config, so it doesn’t load on reboot.

kernel_module 'loop' do
  action :uninstall
end

Unload kernel module.

kernel_module 'loop' do
  action :unload
end

Blacklist a module from loading.

kernel_module 'loop' do
  action :blacklist
end

Disable a kernel module.

kernel_module 'loop' do
  action :disable
end

ksh resource

ksh resource page

Use the ksh resource to execute scripts using the Korn shell (ksh) interpreter. This resource may also use any of the actions and properties that are available to the execute resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Syntax


A ksh resource block executes scripts using ksh:

ksh 'hello world' do
  code <<-EOH
    echo "Hello world!"
    echo "Current directory: " $cwd
  EOH
end

where:

  • code specifies the command to run

The full syntax for all of the properties that are available to the ksh resource is:

ksh 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  path                       Array
  returns                    Integer, Array
  timeout                    Integer, Float
  user                       String, Integer
  umask                      String, Integer
  action                     Symbol # defaults to :run if not specified
end

where:

  • ksh is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • code, creates, cwd, environment, flags, group, path, returns, timeout, user, and umask are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The ksh resource has the following actions:

:nothing
Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it.
:run
Default. Run a script.

Properties


The ksh resource has the following properties:

code
Ruby Type: String

A quoted (” “) string of code to be executed.

creates
Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd
Ruby Type: String

The current working directory from which the command will be run.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags
Ruby Type: String

One or more command line flags that are passed to the interpreter when a command is invoked.

group
Ruby Type: String, Integer

The group name or group ID that must be changed before running a command.

returns
Ruby Type: Integer, Array | Default Value: 0

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match.

timeout
Ruby Type: Integer, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

user
Ruby Type: String, Integer

The user name or user ID that should be changed before running a command.

umask
Ruby Type: String, Integer

The file mode creation mask, or umask.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

launchd resource

launchd resource page

Use the launchd resource to manage system-wide services (daemons) and per-user services (agents) on the macOS platform.

New in Chef Infra Client 12.8.

Syntax


The full syntax for all of the properties that are available to the launchd resource is:

launchd 'name' do
  abandon_process_group           true, false
  backup                          Integer, false
  cookbook                        String
  debug                           true, false
  disabled                        true, false # default value: false
  enable_globbing                 true, false
  enable_transactions             true, false
  environment_variables           Hash
  exit_timeout                    Integer
  group                           String, Integer
  hard_resource_limits            Hash
  inetd_compatibility             Hash
  init_groups                     true, false
  keep_alive                      true, false, Hash
  label                           String # default value: 'name' unless specified
  launch_events                   Hash
  launch_only_once                true, false
  ld_group                        String
  limit_load_from_hosts           Array
  limit_load_to_hosts             Array
  limit_load_to_session_type      Array, String
  low_priority_io                 true, false
  mach_services                   Hash
  mode                            String, Integer
  nice                            Integer
  on_demand                       true, false
  owner                           String, Integer
  path                            String
  plist_hash                      Hash
  process_type                    String
  program                         String
  program_arguments               Array
  queue_directories               Array
  root_directory                  String
  run_at_load                     true, false
  session_type                    String
  sockets                         Hash
  soft_resource_limits            Array
  source                          String
  standard_error_path             String
  standard_in_path                String
  standard_out_path               String
  start_calendar_interval         Hash, Array
  start_interval                  Integer
  start_on_mount                  true, false
  throttle_interval               Integer
  time_out                        Integer
  type                            String # default value: "daemon"
  umask                           Integer
  username                        String
  wait_for_debugger               true, false
  watch_paths                     Array
  working_directory               String
  action                          Symbol # defaults to :create if not specified
end

where:

  • launchd is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • abandon_process_group, backup, cookbook, debug, disabled, enable_globbing, enable_transactions, environment_variables, exit_timeout, group, hard_resource_limits, inetd_compatibility, init_groups, keep_alive, label, launch_events, launch_only_once, ld_group, limit_load_from_hosts, limit_load_to_hosts, limit_load_to_session_type, low_priority_io, mach_services, mode, nice, on_demand, owner, path, plist_hash, process_type, program, program_arguments, queue_directories, root_directory, run_at_load, session_type, sockets, soft_resource_limits, source, standard_error_path, standard_in_path, standard_out_path, start_calendar_interval, start_interval, start_on_mount, throttle_interval, time_out, type, umask, username, wait_for_debugger, watch_paths, and working_directory are the properties available to this resource.

Actions


The launchd resource has the following actions:

:create
Default. Create a launchd property list.
:create_if_missing
Create a launchd property list, if it does not already exist.
:delete
Delete a launchd property list. This will unload a daemon or agent, if loaded.
:disable
Disable a launchd property list.
:enable
Create a launchd property list, and then ensure that it is enabled. If a launchd property list already exists, but does not match, updates the property list to match, and then restarts the daemon or agent.
: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.
:restart
Restart a launchd managed daemon or agent.

Properties


The launchd resource has the following properties:

abandon_process_group
Ruby Type: true, false

If a job dies, all remaining processes with the same process ID may be kept running. Set to true to kill all remaining processes.

backup
Ruby Type: Integer, false

The number of backups to be kept in /var/chef/backup. Set to false to prevent backups from being kept.

cookbook
Ruby Type: String

The name of the cookbook in which the source files are located.

group
Ruby Type: String, Integer

When launchd is run as the root user, the group to run the job as. If the username property is specified and this property is not, this value is set to the default group for the user.

label
Ruby Type: String

The unique identifier for the job.

mode
Ruby Type: Integer, String | Default Value: '0755'

A quoted 3-5 character string that defines the octal mode. For example: '755', '0755', or 00755.

owner
Ruby Type: Integer, String

A string or ID that identifies the group owner by user name, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path
Ruby Type: String

The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the name of the resource block. See “Syntax” section above for more information.

plist_hash
Ruby Type: Hash

A Hash of key value pairs used to create the launchd property list.

session_type
Ruby Type: String

The type of launchd plist to be created. Possible values: system (default) or user.

source
Ruby Type: String

The path to the launchd property list.

type
Ruby Type: String

The type of resource. Possible values: daemon (default), agent.

abandon_process_group
Ruby Type: true, false

If a job dies, all remaining processes with the same process ID may be kept running. Set to true to kill all remaining processes.

debug
Ruby Type: true, false

Sets the log mask to LOG_DEBUG for this job.

disabled
Ruby Type: true, false | Default Value: false

Hints to launchctl to not submit this job to launchd.

enable_globbing
Ruby Type: true, false

Update program arguments before invocation.

enable_transactions
Ruby Type: true, false

Track in-progress transactions; if none, then send the SIGKILL signal.

environment_variables
Ruby Type: Hash

Additional environment variables to set before running a job.

exit_timeout
Ruby Type: Integer | Default Value: 20

The amount of time (in seconds) launchd waits before sending a SIGKILL signal.

hard_resource_limits
Ruby Type: Hash

A Hash of resource limits to be imposed on a job.

inetd_compatibility
Ruby Type: Hash

Specifies if a daemon expects to be run as if it were launched from inetd. Set to wait => true to pass standard input, output, and error file descriptors. Set to wait => false to call the accept system call on behalf of the job, and then pass standard input, output, and error file descriptors.

init_groups
Ruby Type: true, false | Default Value: true

Specify if initgroups is called before running a job.

keep_alive
Ruby Type: true, false, Hash | Default Value: false

Keep a job running continuously (true) or allow demand and conditions on the node to determine if the job keeps running (false).

launch_events
Ruby Type: Hash

Specify higher-level event types to be used as launch-on-demand event sources.

New in Chef Infra Client 15.1

launch_only_once
Ruby Type: true, false

Specify if a job can be run only one time. Set this value to true if a job cannot be restarted without a full machine reboot.

limit_load_from_hosts
Ruby Type: Array

An array of hosts to which this configuration file does not apply, i.e. “apply this configuration file to all hosts not specified in this array”.

limit_load_to_hosts
Ruby Type: Array

An array of hosts to which this configuration file applies.

limit_load_to_session_type
Ruby Type: Array, String

The session type(s) to which this configuration file applies.

low_priority_io
Ruby Type: true, false

Specify if the kernel on the node should consider this daemon to be low priority during file system I/O.

mach_services
Ruby Type: Hash

Specify services to be registered with the bootstrap subsystem.

nice
Ruby Type: Integer

The program scheduling priority value in the range -20 to 20.

on_demand
Ruby Type: true, false

Keep a job alive. Only applies to macOS version 10.4 (and earlier); use keep_alive instead for newer versions.

process_type
Ruby Type: String

The intended purpose of the job: Adaptive, Background, Interactive, or Standard.

program
Ruby Type: String

The first argument of execvp, typically the file name associated with the file to be executed. This value must be specified if program_arguments is not specified, and vice-versa.

program_arguments
Ruby Type: Array

The second argument of execvp. If program is not specified, this property must be specified and will be handled as if it were the first argument.

queue_directories
Ruby Type: Array

An array of non-empty directories which, if any are modified, will cause a job to be started.

root_directory
Ruby Type: String

chroot to this directory, and then run the job.

run_at_load
Ruby Type: true, false | Default Value: false

Launch a job once (at the time it is loaded).

sockets
Ruby Type: Hash

A Hash of on-demand sockets that notify launchd when a job should be run.

soft_resource_limits
Ruby Type: Array

A Hash of resource limits to be imposed on a job.

standard_error_path
Ruby Type: String

The file to which standard error (stderr) is sent.

standard_in_path
Ruby Type: String

The file to which standard input (stdin) is sent.

standard_out_path
Ruby Type: String

The file to which standard output (stdout) is sent.

start_calendar_interval
Ruby Type: Hash

A Hash (similar to crontab) that defines the calendar frequency at which a job is started. For example: { Minute => "0", Hour => "20", Day => "*", Weekday => "1-5", Month => "*" } will run a job at 8:00 PM every day, Monday through Friday, every month of the year.

start_interval
Ruby Type: Integer

The frequency (in seconds) at which a job is started.

start_on_mount
Ruby Type: true, false

Start a job every time a file system is mounted.

throttle_interval
Ruby Type: Integer | Default Value: 10

The frequency (in seconds) at which jobs are allowed to spawn.

time_out
Ruby Type: Integer

The amount of time (in seconds) a job may be idle before it times out. If no value is specified, the default timeout value for launchd will be used.

umask
Ruby Type: Integer

A decimal value to pass to umask before running a job.

username
Ruby Type: String

When launchd is run as the root user, the user to run the job as.

wait_for_debugger
Ruby Type: true, false

Specify if launchd has a job wait for a debugger to attach before executing code.

watch_paths
Ruby Type: Array

An array of paths which, if any are modified, will cause a job to be started.

working_directory
Ruby Type: String

chdir to this directory, and then run the job.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the launchd resource in recipes:

Create a Launch Daemon from a cookbook file

launchd 'com.chef.every15' do
  source 'com.chef.every15.plist'
end

Create a Launch Daemon using keys

launchd 'call.mom.weekly' do
  program '/Library/scripts/call_mom.sh'
  start_calendar_interval 'Weekday' => 7, 'Hourly' => 10
  time_out 300
end

Remove a Launch Daemon

launchd 'com.chef.every15' do
  action :delete
end

link resource

link resource page

Use the link resource to create symbolic or hard links.

A symbolic link—sometimes referred to as a soft link—is a directory entry that associates a file name with a string that contains an absolute or relative path to a file on any file system. In other words, “a file that contains a path that points to another file.” A symbolic link creates a new file with a new inode that points to the inode location of the original file.

A hard link is a directory entry that associates a file with another file in the same file system. In other words, “multiple directory entries to the same file.” A hard link creates a new file that points to the same inode as the original file. On Windows, this resource can be used to create directory junction/reparse points.

Syntax


A link resource block creates symbolic or hard links. For example, to create a hard link from /tmp/file to /etc/file:

link '/tmp/file' do
  to '/etc/file'
  link_type :hard
end

Because the default value for link_type is symbolic, and because properties that are not specified in the resource block will be assigned their default values, the following example creates a symbolic link:

link '/tmp/file' do
  to '/etc/file'
end

The full syntax for all of the properties that are available to the link resource is:

link 'name' do
  group            String, Integer
  link_type        String, Symbol # default value: :symbolic
  mode             Integer, String
  owner            String, Integer
  target_file      String # default value: 'name' unless specified
  to               String
  action           Symbol # defaults to :create if not specified
end

where:

  • link 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.
  • group, link_type, mode, owner, target_file, and to are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The link resource has the following actions:

:create
Default. Create a link. If a link already exists (but does not match), update that link to match.
:delete
Delete a link.
: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 link resource has the following properties:

group
Ruby Type: String, Integer

A group name or ID number that identifies the group associated with a symbolic link.

link_type
Ruby Type: String, Symbol | Default Value: :symbolic
Allowed Values: :symbolic :hard

The type of link: :symbolic or :hard. On Windows, :symbolic will create a junction point if the target is a directory.

mode
Ruby Type: Integer, String | Default Value: 777

If mode is not specified and if the file already exists, the existing mode on the file is used. If mode is not specified, the file does not exist, and the :create action is specified, Chef Infra Client assumes a mask value of '0777' and then applies the umask for the system on which the file is to be created to the mask value. For example, if the umask on a system is '022', Chef Infra Client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

owner
Ruby Type: String, Integer

The owner associated with a symbolic link.

target_file
Ruby Type: String | Default Value: The resource block's name

An optional property to set the target file if it differs from the resource block’s name.

to
Ruby Type: String

The actual file to which the link is to be created.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the link resource in recipes:

Create symbolic links

The following example will create a symbolic link from /tmp/file to /etc/file:

link '/tmp/file' do
  to '/etc/file'
end

Create hard links

The following example will create a hard link from /tmp/file to /etc/file:

link '/tmp/file' do
  to '/etc/file'
  link_type :hard
end

Delete links

The following example will delete the /tmp/file symbolic link and uses the only_if guard to run the test -L command, which verifies that /tmp/file is a symbolic link, and then only deletes /tmp/file if the test passes:

link '/tmp/file' do
  action :delete
  only_if 'test -L /tmp/file'
end

Create multiple symbolic links

The following example creates symbolic links from two files in the /vol/webserver/cert/ directory to files located in the /etc/ssl/certs/ directory:

link '/vol/webserver/cert/server.crt' do
  to '/etc/ssl/certs/ssl-cert-name.pem'
end

link '/vol/webserver/cert/server.key' do
  to '/etc/ssl/certs/ssl-cert-name.key'
end

Create platform-specific symbolic links

The following example shows installing a filter module on Apache. The package name is different for different platforms, and for the Red Hat Enterprise Linux family, a symbolic link is required:

include_recipe 'apache2::default'

case node['platform_family']
when 'debian'
  ...
when 'suse'
  ...
when 'rhel', 'fedora'
  ...

  link '/usr/lib64/httpd/modules/mod_apreq.so' do
    to      '/usr/lib64/httpd/modules/mod_apreq2.so'
    only_if 'test -f /usr/lib64/httpd/modules/mod_apreq2.so'
  end

  link '/usr/lib/httpd/modules/mod_apreq.so' do
    to      '/usr/lib/httpd/modules/mod_apreq2.so'
    only_if 'test -f /usr/lib/httpd/modules/mod_apreq2.so'
  end
end

...

For the complete recipe, see https://github.com/onehealth-cookbooks/apache2/blob/68bdfba4680e70b3e90f77e40223dd535bf22c17/recipes/mod_apreq2.rb.

Create Windows junction/reparse points

This example demonstrates how to create a directory junction/reparse point. In this example, C:\destination will be a junction/reparse point to the C:\source directory.

directory 'C:/source'

link 'C:/destination' do
    link_type :symbolic
    to 'C:/source'
end

locale resource

locale resource page

Use the locale resource to set the system’s locale on Debian and Windows systems. Windows support was added in Chef Infra Client 16.0

New in Chef Infra Client 14.5.

Syntax


The full syntax for all of the properties that are available to the locale resource is:

locale 'name' do
  lang        String
  lc_env      Hash
  action      Symbol # defaults to :update if not specified
end

where:

  • locale is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • lang and lc_env are the properties available to this resource.

Actions


The locale 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.
:update
Updates the system’s locale.

Properties


The locale resource has the following properties:

lang
Ruby Type: String

Sets the default system language.

lc_env
Ruby Type: Hash

Sets the locale category that corresponds to environment variable.

  • lc_env is a hash of LC* env variables in the form of ({‘LC_ENV_VARIABLE’ => ‘VALUE’}).
  • Valid values that can be used to set LC_ENV_VARIABLE are: LC_ADDRESS, LC_COLLATE, LC_CTYPE, LC_IDENTIFICATION, LC_MEASUREMENT, LC_MESSAGES, LC_MONETARY, LC_NAME, LC_NUMERIC, LC_PAPER, LC_TELEPHONE and LC_TIME.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the locale resource in recipes:

Set the lang to ‘en_US.UTF-8’

  locale 'set system locale' do
    lang 'en_US.UTF-8'
  end

log resource

log resource page

Use the log resource to create log entries. The log resource behaves like any other resource: built into the resource collection during the compile phase, and then run during the execution phase. (To create a log entry that is not built into the resource collection, use Chef::Log instead of the log resource.)

Note

By default, every log resource that executes will count as an updated resource in the updated resource count at the end of a Chef run. You can disable this behavior by adding count_log_resource_updates false to your Chef client.rb configuration file.

Syntax


A log resource block adds messages to the log file based on events that occur during a Chef Infra Client run:

log 'message' do
  message 'A message add to the log.'
  level :info
end

The full syntax for all of the properties that are available to the log resource is:

log 'name' do
  level        Symbol # default value: :info
  message      String # default value: 'name' unless specified
  action       Symbol # defaults to :write if not specified
end

where:

  • log is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • level and message are the properties available to this resource.

Properties


The log resource has the following properties:

level

Ruby Type: Symbol | Default Value: :info

The logging level for displaying this message. Options (in order of priority): :debug, :info, :warn, :error, and :fatal.

message

Ruby Type: String | Default Value: The resource block's name

The message to be added to a log file. Default value: the name of the resource block. See “Syntax” section above for more information.

Log Entries

Chef::Log will print log entries to the default logger that is configured for the machine on which Chef Infra Client is running. (To create a log entry that is built into the resource collection, use the log resource instead of Chef::Log.)

The following log levels are supported:

Log LevelSyntax
FatalChef::Log.fatal('string')
ErrorChef::Log.error('string')
WarnChef::Log.warn('string')
InfoChef::Log.info('string')
DebugChef::Log.debug('string')

Note

The parentheses are optional, e.g. Chef::Log.info 'string' may be used instead of Chef::Log.info('string').

The following example shows a series of fatal Chef::Log entries:

unless node['splunk']['upgrade_enabled']
  Chef::Log.fatal('The chef-splunk::upgrade recipe was added to the node,')
  Chef::Log.fatal('but the attribute `node["splunk"]["upgrade_enabled"]` was not set.')
  Chef::Log.fatal('I am bailing here so this node does not upgrade.')
  raise
end

service 'splunk_stop' do
  service_name 'splunk'
  supports status: true
  action :stop
end

if node['splunk']['is_server']
  splunk_package = 'splunk'
  url_type = 'server'
else
  splunk_package = 'splunkforwarder'
  url_type = 'forwarder'
end

splunk_installer splunk_package do
  url node['splunk']['upgrade']["#{url_type}_url"]
end

if node['splunk']['accept_license']
  execute 'splunk-unattended-upgrade' do
    command "#{splunk_cmd} start --accept-license --answer-yes"
  end
else
  Chef::Log.fatal('You did not accept the license (set node["splunk"]["accept_license"] to true)')
  Chef::Log.fatal('Splunk is stopped and cannot be restarted until the license is accepted!')
  raise
end

The full recipe is the upgrade.rb recipe of the chef-splunk cookbook that is maintained by Chef.

The following example shows using multiple Chef::Log entry types:

...

begin
  aws = Chef::DataBagItem.load(:aws, :main)
  Chef::Log.info("Loaded AWS information from DataBagItem aws[#{aws['id']}]")
rescue
  Chef::Log.fatal("Could not find the 'main' item in the 'aws' data bag")
  raise
end

...

The full recipe is in the ebs_volume.rb recipe of the database cookbook that is maintained by Chef.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the log resource in recipes:

Set default logging level

log 'a string to log'

Set debug logging level

log 'a debug string' do
  level :debug
end

Add a message to a log file

log 'message' do
  message 'This is the message that will be added to the log.'
  level :info
end

macos_userdefaults resource

macos_userdefaults resource page

Use the macos_userdefaults resource to manage the macOS user defaults system. The properties of this resource are passed to the defaults command, and the parameters follow the convention of that command. See the defaults(1) man page for details on how the tool works.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the macos_userdefaults resource is:

macos_userdefaults 'name' do
  domain      String # default value: NSGlobalDomain: the global domain.
  host        String, Symbol
  key         String
  sudo        true, false # default value: false
  type        String
  user        String
  value       Integer, Float, String, true, false, Hash, Array
  action      Symbol # defaults to :write if not specified
end

where:

  • macos_userdefaults is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • domain, host, key, sudo, type, user, and value are the properties available to this resource.

Actions


The macos_userdefaults resource has the following actions:

:delete
Remove a setting key from the specified domain.
: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.
:write
Default. Writes the setting to the specified domain.

Properties


The macos_userdefaults resource has the following properties:

domain
Ruby Type: String | Default Value: NSGlobalDomain: the global domain.

The domain that the user defaults belong to.

host
Ruby Type: String, Symbol

Set either :current or a hostname to set the user default at the host level.

New in Chef Infra Client 16.3

key
Ruby Type: String | REQUIRED

The preference key.

sudo
Ruby Type: true, false | Default Value: false

Set to true if the setting you wish to modify requires privileged access. This requires passwordless sudo for the ‘/usr/bin/defaults’ command to be setup for the user running Chef Infra Client.

type
Ruby Type: String
Allowed Values: "array", "bool", "dict", "float", "int", "string"

The value type of the preference key.

user
Ruby Type: String

The system user that the default will be applied to.

value
Ruby Type: Integer, Float, String, true, false, Hash, Array | REQUIRED

The value of the key. Note: With the type property set to bool, String forms of Boolean true/false values that Apple accepts in the defaults command will be coerced: 0/1, ‘TRUE’/‘FALSE,’ ‘true’/false’, ‘YES’/‘NO’, or ‘yes’/‘no’.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the macos_userdefaults resource in recipes:

Specify a global domain value

macos_userdefaults 'Full keyboard access to all controls' do
  key 'AppleKeyboardUIMode'
  value 2
end

Setting a value on a specific domain

macos_userdefaults 'Enable macOS firewall' do
  domain '/Library/Preferences/com.apple.alf'
  key 'globalstate'
  value 1
end

Specifying the type of a key to skip automatic type detection

macos_userdefaults 'Finder expanded save dialogs' do
  key 'NSNavPanelExpandedStateForSaveMode'
  value 'TRUE'
  type 'bool'
end

macports_package resource

macports_package resource page

Use the macports_package resource to manage packages for the macOS platform.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, 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


A macports_package resource block manages a package on a node, typically by installing it. The simplest use of the macports_package resource is:

macports_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the macports_package resource is:

macports_package 'name' do
  options                    String
  package_name               String
  source                     String
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • macports_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps 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 macports_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
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.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The macports_package resource has the following properties:

options
Ruby Type: String

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the macports_package resource in recipes:

Install a package

macports_package 'name of package' do
  action :install
end

mdadm resource

mdadm resource page

Use the mdadm resource to manage RAID devices in a Linux environment using the mdadm utility. The mdadm resource will create and assemble an array, but it will not create the config file that is used to persist the array upon reboot. If the config file is required, it must be done by specifying a template with the correct array layout, and then by using the mount resource to create a file systems table (fstab) entry.

Syntax


The mdadm resource has the following syntax:

mdadm 'name' do
  bitmap           String
  chunk            Integer # default value: 16
  devices          Array
  layout           String
  level            Integer # default value: 1
  metadata         String # default value: "0.90"
  raid_device      String # default value: 'name' unless specified
  action           Symbol # defaults to :create if not specified
end

where:

  • mdadm is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • bitmap, chunk, devices, layout, level, metadata, and raid_device are the properties available to this resource.

Actions


The mdadm resource has the following actions:

:assemble
Assemble a previously created array into an active array.
:create
Default. Create an array with per-device superblocks. If an array already exists (but does not match), update that array to match.
:nothing
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.
:stop
Stop an active array.

Properties


The mdadm resource has the following properties:

bitmap
Ruby Type: String

The path to a file in which a write-intent bitmap is stored.

chunk
Ruby Type: Integer | Default Value: 16

The chunk size. This property should not be used for a RAID 1 mirrored pair (i.e. when the level property is set to 1).

devices
Ruby Type: Array

The devices to be part of a RAID array.

layout
Ruby Type: String

The RAID5 parity algorithm. Possible values: left-asymmetric (or la), left-symmetric (or ls), right-asymmetric (or ra), or right-symmetric (or rs).

level
Ruby Type: Integer | Default Value: 1

The RAID level.

metadata
Ruby Type: String | Default Value: "0.90"

The superblock type for RAID metadata.

raid_device
Ruby Type: String | Default Value: The resource block's name

An optional property to specify the name of the RAID device if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the mdadm resource in recipes:

Create and assemble a RAID 0 array

The mdadm command can be used to create RAID arrays. For example, a RAID 0 array named /dev/md0 with 10 devices would have a command similar to the following:

mdadm --create /dev/md0 --level=0 --raid-devices=10 /dev/s01.../dev/s10

where /dev/s01 .. /dev/s10 represents 10 devices (01, 02, 03, and so on). This same command, when expressed as a recipe using the mdadm resource, would be similar to:

mdadm '/dev/md0' do
  devices [ '/dev/s01', ... '/dev/s10' ]
  level 0
  action :create
end

(again, where /dev/s01 .. /dev/s10 represents devices /dev/s01, /dev/s02, /dev/s03, and so on).

Create and assemble a RAID 1 array

mdadm '/dev/md0' do
  devices [ '/dev/sda', '/dev/sdb' ]
  level 1
  action [ :create, :assemble ]
end

Create and assemble a RAID 5 array

The mdadm command can be used to create RAID arrays. For example, a RAID 5 array named /dev/sd0 with 4, and a superblock type of 0.90 would be similar to:

mdadm '/dev/sd0' do
  devices [ '/dev/s1', '/dev/s2', '/dev/s3', '/dev/s4' ]
  level 5
  metadata '0.90'
  chunk 32
  action :create
end

mount resource

mount resource page

Use the mount resource to manage a mounted file system.

Syntax


The full syntax for all of the properties that are available to the mount resource is:

mount 'name' do
  device           String
  device_type      String, Symbol # default value: :device
  domain           String
  dump             Integer, false # default value: 0
  enabled          true, false # default value: false
  fsck_device      String # default value: "-"
  fstype           String # default value: "auto"
  mount_point      String # default value: 'name' unless specified
  options          Array, String # default value: ["defaults"]
  pass             Integer, false # default value: 2
  password         String
  supports         Array, Hash
  username         String
  action           Symbol # defaults to :mount if not specified
end

where:

  • mount is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • device, device_type, domain, dump, enabled, fsck_device, fstype, mount_point, options, pass, password, supports, and username are the properties available to this resource.

Actions


The mount resource has the following actions:

:disable
Remove an entry from the file systems table (fstab).
:enable
Add an entry to the file systems table (fstab).
:mount
Default. Mount a device.
:nothing
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.
:remount
Remount a device.
:umount
Unmount a device.
:unmount
Alias for :umount action.

Properties


The mount resource has the following properties:

device
Ruby Type: String

Required for :umount and :remount actions (for the purpose of checking the mount command output for presence). The special block device or remote node, a label, or a uuid to be mounted.

device_type
Ruby Type: String, Symbol | Default Value: :device
Allowed Values: :device, :label, :uuid

The type of device: :device, :label, or :uuid

domain
Ruby Type: String

Windows only: Use to specify the domain in which the username and password are located.

dump
Ruby Type: Integer, false | Default Value: 0

The dump frequency (in days) used while creating a file systems table (fstab) entry.

enabled
Ruby Type: true, false | Default Value: false

Use to specify if a mounted file system is enabled.

fsck_device
Ruby Type: String | Default Value: -

Solaris only: The fsck device.

fstype
Ruby Type: String | Default Value: auto

The file system type (fstype) of the device.

mount_point
Ruby Type: String | Default Value: The resource block's name

The directory (or path) in which the device is to be mounted. Defaults to the name of the resource block if not provided.

options
Ruby Type: Array, String | Default Value: ["defaults"]

An array or comma separated list of options for the mount.

pass
Ruby Type: Integer, false | Default Value: 2

The pass number used by the file system check (fsck) command while creating a file systems table (fstab) entry.

password
Ruby Type: String

Windows only:. Use to specify the password for username.

supports
Ruby Type: Array, Hash

Specify a Hash of supported mount features. Default value: remount: false (preferred). Array defaults to remount: true (non-preferred).

username
Ruby Type: String

Windows only: Use to specify the user name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the mount resource in recipes:

Mount a labeled file system

mount '/mnt/volume1' do
  device 'volume1'
  device_type :label
  fstype 'xfs'
  options 'rw'
end

Mount a local block drive

mount '/mnt/local' do
  device '/dev/sdb1'
  fstype 'ext3'
end

Mount a non-block file system

mount '/mount/tmp' do
  pass     0
  fstype   'tmpfs'
  device   '/dev/null'
  options  'nr_inodes=999k,mode=755,size=500m'
  action   [:mount, :enable]
end

Mount and add to the file systems table

mount '/export/www' do
  device 'nas1prod:/export/web_sites'
  fstype 'nfs'
  options 'rw'
  action [:mount, :enable]
end

Mount a remote file system

mount '/export/www' do
  device 'nas1prod:/export/web_sites'
  fstype 'nfs'
  options 'rw'
end

Mount a remote folder in Microsoft Windows

mount 'T:' do
  action :mount
  device '\\\\hostname.example.com\\folder'
end

Unmount a remote folder in Microsoft Windows

mount 'T:' do
  action :umount
  device '\\\\hostname.example.com\\D$'
end

Stop a service, do stuff, and then restart it

The following example shows how to use the execute, service, and mount resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following:

  • Checks to see if the Amazon EC2 node has MySQL
  • If the node has MySQL, stops MySQL
  • Installs MySQL
  • Mounts the node
  • Restarts MySQL
# the following code sample comes from the ``server_ec2``
# recipe in the following cookbook:
# https://github.com/chef-cookbooks/mysql

if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path']))

  service 'mysql' do
    action :stop
  end

  execute 'install-mysql' do
    command "mv #{node['mysql']['data_dir']} #{node['mysql']['ec2_path']}"
    not_if do FileTest.directory?(node['mysql']['ec2_path']) end
  end

  [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir|
    directory dir do
      owner 'mysql'
      group 'mysql'
    end
  end

  mount node['mysql']['data_dir'] do
    device node['mysql']['ec2_path']
    fstype 'none'
    options 'bind,rw'
    action [:mount, :enable]
  end

  service 'mysql' do
    action :start
  end

end

where

  • the two service resources are used to stop, and then restart the MySQL service
  • the execute resource is used to install MySQL
  • the mount resource is used to mount the node and enable MySQL

msu_package resource

msu_package resource page

Use the msu_package resource to install Microsoft Update(MSU) packages on Microsoft Windows machines.

New in Chef Infra Client 12.17.

Syntax


The full syntax for all of the properties that are available to the msu_package resource is:

msu_package 'name' do
  checksum          String
  options           String
  package_name      String
  source            String
  timeout           String, Integer # default value: 3600
  action            Symbol # defaults to :install if not specified
end

where:

  • msu_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.
  • checksum, options, package_name, source, and timeout are the properties available to this resource.

Actions


The msu_package 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.

Properties


The msu_package resource has the following properties:

checksum
Ruby Type: String

SHA-256 digest used to verify the checksum of the downloaded MSU package.

options
Ruby Type: String

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

The local file path or URL for the MSU package.

timeout
Ruby Type: String, Integer | Default Value: 3600

The amount of time (in seconds) to wait before timing out.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the msu_package resource in recipes:

Using local path in source

msu_package 'Install Windows 2012R2 Update KB2959977' do
  source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu'
  action :install
end
msu_package 'Remove Windows 2012R2 Update KB2959977' do
  source 'C:\Users\xyz\AppData\Local\Temp\Windows8.1-KB2959977-x64.msu'
  action :remove
end

Using URL in source

msu_package 'Install Windows 2012R2 Update KB2959977' do
  source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu'
  action :install
end
msu_package 'Remove Windows 2012R2 Update KB2959977' do
  source 'https://s3.amazonaws.com/my_bucket/Windows8.1-KB2959977-x64.msu'
  action :remove
end

notify_group resource

notify_group resource page

The notify_group resource does nothing, and always fires notifications which are set on it. Use it to DRY blocks of notifications that are common to multiple resources, and provide a single target for other resources to notify. Unlike most resources, its default action is :nothing.

New in Chef Infra Client 15.8.

Syntax


The full syntax for all of the properties that are available to the notify_group resource is:

notify_group 'name' do
  action      Symbol # defaults to :nothing if not specified
end

where:

  • notify_group 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.

Properties


This resource does not have any properties.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

ohai resource

ohai resource page

Use the ohai resource to reload the Ohai configuration on a node. This allows recipes that change system attributes (like a recipe that adds a user) to refer to those attributes later on during the Chef Infra Client run.

Syntax


The full syntax for all of the properties that are available to the ohai resource is:

ohai 'name' do
  plugin      String
  action      Symbol # defaults to :reload if not specified
end

where:

  • ohai is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • plugin is the property available to this resource.

Actions


The ohai 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.
:reload
Reloads the Ohai data.

Properties


The ohai resource has the following properties:

plugin
Ruby Type: String

Specific Ohai attribute data to reload. This property behaves similar to specifying attributes when running Ohai on the command line and takes the attribute that you wish to reload instead of the actual plugin name. For instance, you can pass ipaddress to reload node['ipaddress'] even though that data comes from the Network plugin. If this property is not specified, Chef Infra Client will reload all plugins.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the ohai resource in recipes:

Reload All Ohai Plugins

ohai 'reload' do
  action :reload
end

Reload A Single Ohai Plugin

ohai 'reload' do
  plugin 'ipaddress'
  action :reload
end

Reload Ohai after a new user is created

ohai 'reload_passwd' do
  action :nothing
  plugin 'etc'
end

user 'daemon_user' do
  home '/dev/null'
  shell '/sbin/nologin'
  system true
  notifies :reload, 'ohai[reload_passwd]', :immediately
end

ruby_block 'just an example' do
  block do
    # These variables will now have the new values
    puts node['etc']['passwd']['daemon_user']['uid']
    puts node['etc']['passwd']['daemon_user']['gid']
  end
end

ohai_hint resource

ohai_hint resource page

Use the ohai_hint resource to aid in configuration detection by passing hint data to Ohai.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the ohai_hint resource is:

ohai_hint 'name' do
  compile_time      true, false # default value: true
  content           Hash
  hint_name         String # default value: 'name' unless specified
  action            Symbol # defaults to :create if not specified
end

where:

  • ohai_hint is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • compile_time, content, and hint_name are the properties available to this resource.

Actions


The ohai_hint resource has the following actions:

:create
Default. Create an Ohai hint file.
:delete
Delete an Ohai hint file.
:nothing
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 ohai_hint resource has the following properties:

compile_time
Ruby Type: true, false | Default Value: true

Determines whether or not the resource is executed during the compile time phase.

content
Ruby Type: Hash

Values to include in the hint file.

hint_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the hint name if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the ohai_hint resource in recipes:

Create a hint file

ohai_hint 'example' do
  content a: 'test_content'
end

Create a hint file with a name that does not match the resource name

ohai_hint 'example' do
  hint_name 'custom'
end

Create a hint file that is not loaded at compile time

ohai_hint 'example' do
  compile_time false
end

Delete a hint file

ohai_hint 'example' do
  action :delete
end

openbsd_package resource

openbsd_package resource page

Use the openbsd_package resource to manage packages for the OpenBSD platform.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, 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


A openbsd_package resource block manages a package on a node, typically by installing it. The simplest use of the openbsd_package resource is:

openbsd_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the openbsd_package resource is:

openbsd_package 'name' do
  options           String
  package_name      String
  source            String
  timeout           String, Integer
  version           String, Array
  action            Symbol # defaults to :install if not specified
end

where:

  • openbsd_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 openbsd_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
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 package.

Properties


The openbsd_package resource has the following properties:

options
Ruby Type: String

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the openbsd_package resource in recipes:

Install a package

openbsd_package 'name of package' do
  action :install
end

openssl_dhparam resource

openssl_dhparam resource page

Use the openssl_dhparam resource to generate dhparam.pem files. If a valid dhparam.pem file is found at the specified location, no new file will be created. If a file is found at the specified location but it is not a valid dhparam.pem file, it will be overwritten.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the openssl_dhparam resource is:

openssl_dhparam 'name' do
  generator       Integer # default value: 2
  group           String, Integer
  key_length      Integer # default value: 2048
  mode            Integer, String # default value: "0640"
  owner           String, Integer
  path            String # default value: 'name' unless specified
  action          Symbol # defaults to :create if not specified
end

where:

  • openssl_dhparam is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • generator, group, key_length, mode, owner, and path are the properties available to this resource.

Actions


The openssl_dhparam resource has the following actions:

:create
Default. Create the dhparam.pem file.
:nothing
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 openssl_dhparam resource has the following properties:

generator
Ruby Type: Integer | Default Value: 2
Allowed Values: 2, 5

The desired Diffie-Hellmann generator.

group
Ruby Type: String, Integer

The group ownership applied to all files created by the resource.

key_length
Ruby Type: Integer | Default Value: 2048
Allowed Values: 1024, 2048, 4096, 8192

The desired bit length of the generated key.

mode
Ruby Type: Integer, String | Default Value: 0640

The permission mode applied to all files created by the resource.

owner
Ruby Type: String, Integer

The owner applied to all files created by the resource.

path
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the path to write the file to if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the openssl_dhparam resource in recipes:

Create a dhparam file

openssl_dhparam '/etc/httpd/ssl/dhparam.pem'

Create a dhparam file with a specific key length

openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do
  key_length 4096
end

Create a dhparam file with specific user/group ownership

openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do
  owner 'www-data'
  group 'www-data'
end

Manually specify the dhparam file path

openssl_dhparam 'httpd_dhparam' do
  path '/etc/httpd/ssl/dhparam.pem'
end

openssl_ec_private_key resource

openssl_ec_private_key resource page

Use the openssl_ec_private_key resource to generate an elliptic curve (EC) private key file. If a valid EC key file can be opened at the specified location, no new file will be created. If the EC key file cannot be opened, either because it does not exist or because the password to the EC key file does not match the password in the recipe, then it will be overwritten.

New in Chef Infra Client 14.4.

Syntax


The full syntax for all of the properties that are available to the openssl_ec_private_key resource is:

openssl_ec_private_key 'name' do
  force           true, false # default value: false
  group           String, Integer
  key_cipher      String # default value: "des3"
  key_curve       String # default value: "prime256v1"
  key_pass        String
  mode            Integer, String # default value: "0600"
  owner           String, Integer
  path            String # default value: 'name' unless specified
  action          Symbol # defaults to :create if not specified
end

where:

  • openssl_ec_private_key is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • force, group, key_cipher, key_curve, key_pass, mode, owner, and path are the properties available to this resource.

Actions


The openssl_ec_private_key resource has the following actions:

:create
Default. Create the EC private key file.
:nothing
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 openssl_ec_private_key resource has the following properties:

force
Ruby Type: true, false | Default Value: false

Force creation of the key even if the same key already exists on the node.

group
Ruby Type: String, Integer

The group ownership applied to all files created by the resource.

key_cipher
Ruby Type: String | Default Value: des3

The designed cipher to use when generating your key. Run openssl list-cipher-algorithms to see available options.

key_curve
Ruby Type: String | Default Value: prime256v1
Allowed Values: "prime256v1", "secp224r1", "secp256k1", "secp384r1", "secp521r1"

The desired curve of the generated key (if key_type is equal to ‘ec’). Run openssl ecparam -list_curves to see available options.

key_pass
Ruby Type: String

The desired passphrase for the key.

mode
Ruby Type: Integer, String | Default Value: 0600

The permission mode applied to all files created by the resource.

owner
Ruby Type: String, Integer

The owner applied to all files created by the resource.

path
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the path to write the file to if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the openssl_ec_private_key resource in recipes:

Generate a new ec privatekey with prime256v1 key curve and default des3 cipher

openssl_ec_private_key '/etc/ssl_files/eckey_prime256v1_des3.pem' do
  key_curve 'prime256v1'
  key_pass 'something'
  action :create
end

Generate a new EC private key with prime256v1 key curve and aes-128-cbc cipher

openssl_ec_private_key '/etc/ssl_files/eckey_prime256v1_des3.pem' do
  key_curve 'prime256v1'
  key_cipher 'aes-128-cbc'
  key_pass 'something'
  action :create
end

openssl_ec_public_key resource

openssl_ec_public_key resource page

Use the openssl_ec_public_key resource to generate elliptic curve (EC) public key files from a given EC private key.

New in Chef Infra Client 14.4.

Syntax


The full syntax for all of the properties that are available to the openssl_ec_public_key resource is:

openssl_ec_public_key 'name' do
  group                    String, Integer
  mode                     Integer, String # default value: "0640"
  owner                    String, Integer
  path                     String # default value: 'name' unless specified
  private_key_content      String
  private_key_pass         String
  private_key_path         String
  action                   Symbol # defaults to :create if not specified
end

where:

  • openssl_ec_public_key is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • group, mode, owner, path, private_key_content, private_key_pass, and private_key_path are the properties available to this resource.

Actions


The openssl_ec_public_key resource has the following actions:

:create
: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 openssl_ec_public_key resource has the following properties:

group
Ruby Type: String, Integer

The group ownership applied to all files created by the resource.

mode
Ruby Type: Integer, String | Default Value: 0640

The permission mode applied to all files created by the resource.

owner
Ruby Type: String, Integer

The owner applied to all files created by the resource.

path
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the path to write the file to if it differs from the resource block’s name.

private_key_content
Ruby Type: String

The content of the private key including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk

private_key_pass
Ruby Type: String

The passphrase of the provided private key.

private_key_path
Ruby Type: String

The path to the private key file.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the openssl_ec_public_key resource in recipes:

Generate new EC public key from a private key on disk

openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3.pub' do
  private_key_path '/etc/ssl_files/eckey_prime256v1_des3.pem'
  private_key_pass 'something'
  action :create
end

Generate new ec public key by passing in a private key

openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3_2.pub' do
  private_key_content "-----BEGIN EC PRIVATE KEY-----
MHcCAQEEII2VAU9re44mAUzYPWCg+qqwdmP8CplsEg0b/DYPXLg2oAoGCCqGSM49
AwEHoUQDQgAEKkpMCbIQ2C6Qlp/B+Odp1a9Y06Sm8yqPvCVIkWYP7M8PX5+RmoIv
jGBVf/+mVBx77ji3NpTilMUt2KPZ87lZ3w==
-----END EC PRIVATE KEY-----
"
  action :create
end

openssl_rsa_private_key resource

openssl_rsa_private_key resource page

Use the openssl_rsa_private_key resource to generate RSA private key files. If a valid RSA key file can be opened at the specified location, no new file will be created. If the RSA key file cannot be opened, either because it does not exist or because the password to the RSA key file does not match the password in the recipe, it will be overwritten.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the openssl_rsa_private_key resource is:

openssl_rsa_private_key 'name' do
  force           true, false # default value: false
  group           String, Integer
  key_cipher      String # default value: "des3"
  key_length      Integer # default value: 2048
  key_pass        String
  mode            Integer, String # default value: "0600"
  owner           String, Integer
  path            String # default value: 'name' unless specified
  action          Symbol # defaults to :create if not specified
end

where:

  • openssl_rsa_private_key is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • force, group, key_cipher, key_length, key_pass, mode, owner, and path are the properties available to this resource.

Actions


The openssl_rsa_private_key resource has the following actions:

:create
: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 openssl_rsa_private_key resource has the following properties:

force
Ruby Type: true, false | Default Value: false

Force creation of the key even if the same key already exists on the node.

group
Ruby Type: String, Integer

The group ownership applied to all files created by the resource.

key_cipher
Ruby Type: String | Default Value: des3

The designed cipher to use when generating your key. Run openssl list-cipher-algorithms to see available options.

key_length
Ruby Type: Integer | Default Value: 2048
Allowed Values: 1024, 2048, 4096, 8192

The desired bit length of the generated key.

key_pass
Ruby Type: String

The desired passphrase for the key.

mode
Ruby Type: Integer, String | Default Value: 0600

The permission mode applied to all files created by the resource.

owner
Ruby Type: String, Integer

The owner applied to all files created by the resource.

path
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the path to write the file to if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the openssl_rsa_private_key resource in recipes:

Generate new 2048bit key with the default des3 cipher

openssl_rsa_private_key '/etc/ssl_files/rsakey_des3.pem' do
  key_length 2048
  action :create
end

Generate new 1024bit key with the aes-128-cbc cipher

openssl_rsa_key '/etc/ssl_files/rsakey_aes128cbc.pem' do
  key_length 1024
  key_cipher 'aes-128-cbc'
  action :create
end

openssl_rsa_public_key resource

openssl_rsa_public_key resource page

Use the openssl_rsa_public_key resource to generate RSA public key files for a given RSA private key.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the openssl_rsa_public_key resource is:

openssl_rsa_public_key 'name' do
  group                    String, Integer
  mode                     Integer, String # default value: "0640"
  owner                    String, Integer
  path                     String # default value: 'name' unless specified
  private_key_content      String
  private_key_pass         String
  private_key_path         String
  action                   Symbol # defaults to :create if not specified
end

where:

  • openssl_rsa_public_key is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • group, mode, owner, path, private_key_content, private_key_pass, and private_key_path are the properties available to this resource.

Actions


The openssl_rsa_public_key resource has the following actions:

:create
Default. Create the RSA public key.
:nothing
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 openssl_rsa_public_key resource has the following properties:

group
Ruby Type: String, Integer

The group ownership applied to all files created by the resource.

mode
Ruby Type: Integer, String | Default Value: 0640

The permission mode applied to all files created by the resource.

owner
Ruby Type: String, Integer

The owner applied to all files created by the resource.

path
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the path to the public key if it differs from the resource block’s name.

private_key_content
Ruby Type: String

The content of the private key, including new lines. This property is used in place of private_key_path in instances where you want to avoid having to first write the private key to disk.

private_key_pass
Ruby Type: String

The passphrase of the provided private key.

private_key_path
Ruby Type: String

The path to the private key file.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the openssl_rsa_public_key resource in recipes:

Generate new public key from a private key on disk

openssl_rsa_public_key '/etc/ssl_files/rsakey_des3.pub' do
  private_key_path '/etc/ssl_files/rsakey_des3.pem'
  private_key_pass 'something'
  action :create
end

Generate new public key by passing in a private key

openssl_rsa_public_key '/etc/ssl_files/rsakey_2.pub' do
  private_key_pass 'something'
  private_key_content "-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,5EE0AE9A5FE3342E

yb930kj5/4/nd738dPx6XdbDrMCvqkldaz0rHNw8xsWvwARrl/QSPwROG3WY7ROl
EUttVlLaeVaqRPfQbmTUfzGI8kTMmDWKjw52gJUx2YJTYRgMHAB0dzYIRjeZAaeS
ypXnEfouVav+jKTmmehr1WuVKbzRhQDBSalzeUwsPi2+fb3Bfuo1dRW6xt8yFuc4
Akv1hCglymPzPHE2L0nSGjcgA2DZu+/S8/wZ4E63442NHPzO4VlLvpNvJrYpEWq9
B5mJzcdXPeOTjqd13olNTlOZMaKxu9QShu50GreCTVsl8VRkK8NtwbWuPGBZlIFa
jzlS/RaLuzNzfajaKMkcIYco9t7gN2DwnsACHKqEYT8248Ii3NQ+9/M5YcmpywQj
WGr0UFCSAdCky1lRjwT+zGQKohr+dVR1GaLem+rSZH94df4YBxDYw4rjsKoEhvXB
v2Vlx+G7Vl2NFiZzxUKh3MvQLr/NDElpG1pYWDiE0DIG13UqEG++cS870mcEyfFh
SF2SXYHLWyAhDK0viRDChJyFMduC4E7a2P9DJhL3ZvM0KZ1SLMwROc1XuZ704GwO
YUqtCX5OOIsTti1Z74jQm9uWFikhgWByhVtu6sYL1YTqtiPJDMFhA560zp/k/qLO
FKiM4eUWV8AI8AVwT6A4o45N2Ru8S48NQyvh/ADFNrgJbVSeDoYE23+DYKpzbaW9
00BD/EmUQqaQMc670vmI+CIdcdE7L1zqD6MZN7wtPaRIjx4FJBGsFoeDShr+LoTD
rwbadwrbc2Rf4DWlvFwLJ4pvNvdtY3wtBu79UCOol0+t8DVVSPVASsh+tp8XncDE
KRljj88WwBjX7/YlRWvQpe5y2UrsHI0pNy8TA1Xkf6GPr6aS2TvQD5gOrAVReSse
/kktCzZQotjmY1odvo90Zi6A9NCzkI4ZLgAuhiKDPhxZg61IeLppnfFw0v3H4331
V9SMYgr1Ftov0++x7q9hFPIHwZp6NHHOhdHNI80XkHqtY/hEvsh7MhFMYCgSY1pa
K/gMcZ/5Wdg9LwOK6nYRmtPtg6fuqj+jB3Rue5/p9dt4kfom4etCSeJPdvP1Mx2I
eNmyQ/7JN9N87FsfZsIj5OK9OB0fPdj0N0m1mlHM/mFt5UM5x39u13QkCt7skEF+
yOptXcL629/xwm8eg4EXnKFk330WcYSw+sYmAQ9ZTsBxpCMkz0K4PBTPWWXx63XS
c4J0r88kbCkMCNv41of8ceeGzFrC74dG7i3IUqZzMzRP8cFeps8auhweUHD2hULs
XwwtII0YQ6/Fw4hgGQ5//0ASdvAicvH0l1jOQScHzXC2QWNg3GttueB/kmhMeGGm
sHOJ1rXQ4oEckFvBHOvzjP3kuRHSWFYDx35RjWLAwLCG9odQUApHjLBgFNg9yOR0
jW9a2SGxRvBAfdjTa9ZBBrbjlaF57hq7mXws90P88RpAL+xxCAZUElqeW2Rb2rQ6
Cbz4/AtPekV1CYVodGkPutOsew2zjNqlNH+M8XzfonA60UAH20TEqAgLKwgfgr+a
c+rXp1AupBxat4EHYJiwXBB9XcVwyp5Z+/dXsYmLXzoMOnp8OFyQ9H8R7y9Y0PEu
-----END RSA PRIVATE KEY-----
"
  action :create
end

openssl_x509_certificate resource

openssl_x509_certificate resource page

Use the openssl_x509_certificate resource to generate signed or self-signed, PEM-formatted x509 certificates. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate. If a CA private key and certificate are provided, the certificate will be signed with them.

Note

This resource was renamed from openssl_x509 to openssl_x509_certificate. The legacy name will continue to function, but cookbook code should be updated for the new resource name.

New in Chef Infra Client 14.4.

Syntax


The full syntax for all of the properties that are available to the openssl_x509_certificate resource is:

openssl_x509_certificate 'name' do
  ca_cert_file             String
  ca_key_file              String
  ca_key_pass              String
  city                     String
  common_name              String
  country                  String
  csr_file                 String
  email                    String
  expire                   Integer # default value: 365
  extensions               Hash
  group                    String, Integer
  key_curve                String # default value: "prime256v1"
  key_file                 String
  key_length               Integer # default value: 2048
  key_pass                 String
  key_type                 String # default value: "rsa"
  mode                     Integer, String
  org                      String
  org_unit                 String
  owner                    String, Integer
  path                     String # default value: 'name' unless specified
  renew_before_expiry      Integer
  state                    String
  subject_alt_name         Array
  action                   Symbol # defaults to :create if not specified
end

where:

  • openssl_x509_certificate is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • ca_cert_file, ca_key_file, ca_key_pass, city, common_name, country, csr_file, email, expire, extensions, group, key_curve, key_file, key_length, key_pass, key_type, mode, org, org_unit, owner, path, renew_before_expiry, state, and subject_alt_name are the properties available to this resource.

Actions


The openssl_x509_certificate resource has the following actions:

:create
Default. Create the certificate file.
:nothing
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 openssl_x509_certificate resource has the following properties:

ca_cert_file
Ruby Type: String

The path to the CA X509 Certificate on the filesystem. If the ca_cert_file property is specified, the ca_key_file property must also be specified, the certificate will be signed with them.

ca_key_file
Ruby Type: String

The path to the CA private key on the filesystem. If the ca_key_file property is specified, the ca_cert_file property must also be specified, the certificate will be signed with them.

ca_key_pass
Ruby Type: String

The passphrase for CA private key’s passphrase.

city
Ruby Type: String

Value for the L certificate field.

common_name
Ruby Type: String

Value for the CN certificate field.

country
Ruby Type: String

Value for the C certificate field.

csr_file
Ruby Type: String

The path to a X509 Certificate Request (CSR) on the filesystem. If the csr_file property is specified, the resource will attempt to source a CSR from this location. If no CSR file is found, the resource will generate a Self-Signed Certificate and the certificate fields must be specified (common_name at last).

email
Ruby Type: String

Value for the email certificate field.

expire
Ruby Type: Integer | Default Value: 365

Value representing the number of days from now through which the issued certificate cert will remain valid. The certificate will expire after this period.

extensions
Ruby Type: Hash

Hash of X509 Extensions entries, in format { 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true } }.

group
Ruby Type: String, Integer

The group ownership applied to all files created by the resource.

key_curve
Ruby Type: String | Default Value: prime256v1
Allowed Values: "prime256v1", "secp384r1", "secp521r1"

The desired curve of the generated key (if key_type is equal to ‘ec’). Run openssl ecparam -list_curves to see available options.

key_file
Ruby Type: String

The path to a certificate key file on the filesystem. If the key_file property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the key_file property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate.

key_length
Ruby Type: Integer | Default Value: 2048
Allowed Values: 1024, 2048, 4096, 8192

The desired bit length of the generated key (if key_type is equal to ‘rsa’).

key_pass
Ruby Type: String

The passphrase for an existing key’s passphrase.

key_type
Ruby Type: String | Default Value: rsa
Allowed Values: "ec", "rsa"

The desired type of the generated key.

mode
Ruby Type: Integer, String

The permission mode applied to all files created by the resource.

org
Ruby Type: String

Value for the O certificate field.

org_unit
Ruby Type: String

Value for the OU certificate field.

owner
Ruby Type: String, Integer

The owner applied to all files created by the resource.

path
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the path to write the file to if it differs from the resource block’s name.

renew_before_expiry
Ruby Type: Integer

The number of days before the expiry. The certificate will be automatically renewed when the value is reached.

New in Chef Infra Client 15.7

state
Ruby Type: String

Value for the ST certificate field.

subject_alt_name
Ruby Type: Array

Array of Subject Alternative Name entries, in format DNS:example.com or IP:1.2.3.4.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the openssl_x509_certificate resource in recipes:

Create a simple self-signed certificate file

openssl_x509_certificate '/etc/httpd/ssl/mycert.pem' do
  common_name 'www.f00bar.com'
  org 'Foo Bar'
  org_unit 'Lab'
  country 'US'
end

Create a certificate using additional options

openssl_x509_certificate '/etc/ssl_files/my_signed_cert.crt' do
  common_name 'www.f00bar.com'
  ca_key_file '/etc/ssl_files/my_ca.key'
  ca_cert_file '/etc/ssl_files/my_ca.crt'
  expire 365
  extensions(
    'keyUsage' => {
      'values' => %w(
        keyEncipherment
        digitalSignature),
      'critical' => true,
    },
    'extendedKeyUsage' => {
      'values' => %w(serverAuth),
      'critical' => false,
    }
  )
  subject_alt_name ['IP:127.0.0.1', 'DNS:localhost.localdomain']
end

openssl_x509_crl resource

openssl_x509_crl resource page

Use the openssl_x509_crl resource to generate PEM-formatted x509 certificate revocation list (CRL) files.

New in Chef Infra Client 14.4.

Syntax


The full syntax for all of the properties that are available to the openssl_x509_crl resource is:

openssl_x509_crl 'name' do
  ca_cert_file           String
  ca_key_file            String
  ca_key_pass            String
  expire                 Integer # default value: 8
  group                  String, Integer
  mode                   Integer, String
  owner                  String, Integer
  path                   String # default value: 'name' unless specified
  renewal_threshold      Integer # default value: 1
  revocation_reason      Integer # default value: 0
  serial_to_revoke       Integer, String
  action                 Symbol # defaults to :create if not specified
end

where:

  • openssl_x509_crl is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • ca_cert_file, ca_key_file, ca_key_pass, expire, group, mode, owner, path, renewal_threshold, revocation_reason, and serial_to_revoke are the properties available to this resource.

Actions


The openssl_x509_crl resource has the following actions:

:create
Default. Create the certificate revocation list file.
:nothing
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 openssl_x509_crl resource has the following properties:

ca_cert_file
Ruby Type: String | REQUIRED

The path to the CA X509 Certificate on the filesystem. If the ca_cert_file property is specified, the ca_key_file property must also be specified, the CRL will be signed with them.

ca_key_file
Ruby Type: String | REQUIRED

The path to the CA private key on the filesystem. If the ca_key_file property is specified, the ca_cert_file property must also be specified, the CRL will be signed with them.

ca_key_pass
Ruby Type: String

The passphrase for CA private key’s passphrase.

expire
Ruby Type: Integer | Default Value: 8

Value representing the number of days from now through which the issued CRL will remain valid. The CRL will expire after this period.

group
Ruby Type: String, Integer

The group permission for the CRL file.

mode
Ruby Type: Integer, String

The permission mode of the CRL file.

owner
Ruby Type: String, Integer

The owner permission for the CRL file.

path
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the path to write the file to if it differs from the resource block’s name.

renewal_threshold
Ruby Type: Integer | Default Value: 1

Number of days before the expiration. It this threshold is reached, the CRL will be renewed.

revocation_reason
Ruby Type: Integer | Default Value: 0

Reason for the revocation.

serial_to_revoke
Ruby Type: Integer, String

Serial of the X509 Certificate to revoke.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the openssl_x509_crl resource in recipes:

Create a certificate revocation file

openssl_x509_crl '/etc/ssl_test/my_ca.crl' do
  ca_cert_file '/etc/ssl_test/my_ca.crt'
  ca_key_file '/etc/ssl_test/my_ca.key'
end

Create a certificate revocation file for a particular serial

openssl_x509_crl '/etc/ssl_test/my_ca.crl' do
  ca_cert_file '/etc/ssl_test/my_ca.crt'
  ca_key_file '/etc/ssl_test/my_ca.key'
  serial_to_revoke C7BCB6602A2E4251EF4E2827A228CB52BC0CEA2F
end

openssl_x509_request resource

openssl_x509_request resource page

Use the openssl_x509_request resource to generate PEM-formatted x509 certificates requests. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate.

New in Chef Infra Client 14.4.

Syntax


The full syntax for all of the properties that are available to the openssl_x509_request resource is:

openssl_x509_request 'name' do
  city             String
  common_name      String
  country          String
  email            String
  group            String, Integer
  key_curve        String # default value: "prime256v1"
  key_file         String
  key_length       Integer # default value: 2048
  key_pass         String
  key_type         String # default value: "ec"
  mode             Integer, String
  org              String
  org_unit         String
  owner            String, Integer
  path             String # default value: 'name' unless specified
  state            String
  action           Symbol # defaults to :create if not specified
end

where:

  • openssl_x509_request is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • city, common_name, country, email, group, key_curve, key_file, key_length, key_pass, key_type, mode, org, org_unit, owner, path, and state are the properties available to this resource.

Actions


The openssl_x509_request resource has the following actions:

:create
Default. Create the certificate request file.
:nothing
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 openssl_x509_request resource has the following properties:

city
Ruby Type: String

Value for the L certificate field.

common_name
Ruby Type: String | REQUIRED

Value for the CN certificate field.

country
Ruby Type: String

Value for the C certificate field.

email
Ruby Type: String

Value for the email certificate field.

group
Ruby Type: String, Integer

The group ownership applied to all files created by the resource.

key_curve
Ruby Type: String | Default Value: prime256v1
Allowed Values: "prime256v1", "secp384r1", "secp521r1"

The desired curve of the generated key (if key_type is equal to ec). Run openssl ecparam -list_curves to see available options.

key_file
Ruby Type: String

The path to a certificate key file on the filesystem. If the key_file property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the key_file property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate.

key_length
Ruby Type: Integer | Default Value: 2048
Allowed Values: 1024, 2048, 4096, 8192

The desired bit length of the generated key (if key_type is equal to rsa).

key_pass
Ruby Type: String

The passphrase for an existing key’s passphrase.

key_type
Ruby Type: String | Default Value: ec
Allowed Values: "ec", "rsa"

The desired type of the generated key.

mode
Ruby Type: Integer, String

The permission mode applied to all files created by the resource.

org
Ruby Type: String

Value for the O certificate field.

org_unit
Ruby Type: String

Value for the OU certificate field.

owner
Ruby Type: String, Integer

The owner applied to all files created by the resource.

path
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the path to write the file to if it differs from the resource block’s name.

state
Ruby Type: String

Value for the ST certificate field.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the openssl_x509_request resource in recipes:

Generate new EC key and CSR file

openssl_x509_request '/etc/ssl_files/my_ec_request.csr' do
  common_name 'myecrequest.example.com'
  org 'Test Kitchen Example'
  org_unit 'Kitchens'
  country 'UK'
end

Generate a new CSR file from an existing EC key

openssl_x509_request '/etc/ssl_files/my_ec_request2.csr' do
  common_name 'myecrequest2.example.com'
  org 'Test Kitchen Example'
  org_unit 'Kitchens'
  country 'UK'
  key_file '/etc/ssl_files/my_ec_request.key'
end

Generate new RSA key and CSR file

openssl_x509_request '/etc/ssl_files/my_rsa_request.csr' do
  common_name 'myrsarequest.example.com'
  org 'Test Kitchen Example'
  org_unit 'Kitchens'
  country 'UK'
  key_type 'rsa'
end

osx_profile resource

osx_profile resource page

Use the osx_profile resource to manage configuration profiles (.mobileconfig files) on the macOS platform. The osx_profile resource installs profiles by using the uuidgen library to generate a unique ProfileUUID, and then using the profiles command to install the profile on the system.

New in Chef Infra Client 12.7.

Syntax


The full syntax for all of the properties that are available to the osx_profile resource is:

osx_profile 'name' do
  identifier        String
  profile           String, Hash
  profile_name      String # default value: 'name' unless specified
  action            Symbol # defaults to :install if not specified
end

where:

  • osx_profile is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • identifier, profile, and profile_name are the properties available to this resource.

Actions


The osx_profile resource has the following actions:

:install
Default. Install the specified configuration profile.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove the specified configuration profile.

Properties


The osx_profile resource has the following properties:

identifier
Ruby Type: String

Use to specify the identifier for the profile, such as com.company.screensaver.

path
Ruby Type: String

The path to write the profile to disk before loading it.

profile
Ruby Type: String, Hash

Use to specify a profile. This may be the name of a profile contained in a cookbook or a Hash that contains the contents of the profile.

profile_name
Ruby Type: String | Default Value: The resource block's name

Use to specify the name of the profile, if different from the name of the resource block.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the osx_profile resource in recipes:

Install a profile from a cookbook file

osx_profile 'com.company.screensaver.mobileconfig'

Install profile from a hash

profile_hash = {
  'PayloadIdentifier' => 'com.company.screensaver',
  'PayloadRemovalDisallowed' => false,
  'PayloadScope' => 'System',
  'PayloadType' => 'Configuration',
  'PayloadUUID' => '1781fbec-3325-565f-9022-8aa28135c3cc',
  'PayloadOrganization' => 'Chef',
  'PayloadVersion' => 1,
  'PayloadDisplayName' => 'Screensaver Settings',
  'PayloadContent'=> [
    {
      'PayloadType' => 'com.apple.ManagedClient.preferences',
      'PayloadVersion' => 1,
      'PayloadIdentifier' => 'com.company.screensaver',
      'PayloadUUID' => '73fc30e0-1e57-0131-c32d-000c2944c108',
      'PayloadEnabled' => true,
      'PayloadDisplayName' => 'com.apple.screensaver',
      'PayloadContent' => {
        'com.apple.screensaver' => {
          'Forced' => [
            {
              'mcx_preference_settings' => {
                'idleTime' => 0,
              }
            }
          ]
        }
      }
    }
  ]
}

osx_profile 'Install screensaver profile' do
  profile profile_hash
end

Remove profile using identifier in resource name

osx_profile 'com.company.screensaver' do
  action :remove
end

Remove profile by identifier and user friendly resource name

osx_profile 'Remove screensaver profile' do
  identifier 'com.company.screensaver'
  action :remove
end

package resource

package resource page

Use the package resource to manage packages. When the package is installed from a local file (such as with RubyGems, dpkg, or RPM Package Manager), the file must be added to the node using the remote_file or cookbook_file resources.

This resource is the base resource for several other resources used for package management on specific platforms. While it is possible to use each of these specific resources, it is recommended to use the package resource as often as possible.

For more information about specific resources for specific platforms, see the following topics:

Syntax


A package resource block manages a package on a node, typically by installing it. The simplest use of the package resource is:

package 'httpd'

which will install Apache using all of the default options and the default action (:install).

For a package that has different package names, depending on the platform, use a case statement within the package:

package 'Install Apache' do
  case node[:platform]
  when 'redhat', 'centos'
    package_name 'httpd'
  when 'ubuntu', 'debian'
    package_name 'apache2'
  end
end

where:

  • 'redhat', 'centos' will install Apache using the httpd package and 'ubuntu', 'debian' will install it using the apache2 package

The full syntax for all of the properties that are available to the package resource is:

package 'name' do
  allow_downgrade            true, false # Yum, RPM packages only
  arch                       String, Array # Yum packages only
  default_release            String # Apt packages only
  flush_cache                Array
  gem_binary                 String
  homebrew_user              String, Integer # Homebrew packages only
  notifies                   # see description
  options                    String
  package_name               String, Array # defaults to 'name' if not specified
  response_file              String # Apt packages only
  response_file_variables    Hash # Apt packages only
  source                     String
  subscribes                 # see description
  timeout                    String, Integer
  version                    String, Array
  action                     Symbol # defaults to :install if not specified
end

where:

  • package tells Chef Infra Client to manage a package; Chef Infra Client will determine the correct package provider to use based on the platform running on the node
  • 'name' is the name of the package
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state
  • allow_downgrade, arch, default_release, flush_cache, gem_binary, homebrew_user, options, package_name, response_file, response_file_variables, source, recursive, timeout, and version are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Gem Package Options

The RubyGems package provider attempts to use the RubyGems API to install gems without spawning a new process, whenever possible. A gems command to install will be spawned under the following conditions:

  • When a gem_binary property is specified (as a hash, a string, or by a .gemrc file), Chef Infra Client will run that command to examine its environment settings and then again to install the gem.
  • When install options are specified as a string, Chef Infra Client will span a gems command with those options when installing the gem.
  • The Chef installer will search the PATH for a gem command rather than defaulting to the current gem environment. As part of enforce_path_sanity, the bin directories area added to the PATH, which means when there are no other proceeding RubyGems, the installation will still be operated against it.

Specify with Hash

If an explicit gem_binary parameter is not being used with the gem_package resource, it is preferable to provide the install options as a hash. This approach allows the provider to install the gem without needing to spawn an external gem process.

The following RubyGems options are available for inclusion within a hash and are passed to the RubyGems DependencyInstaller:

  • :env_shebang
  • :force
  • :format_executable
  • :ignore_dependencies
  • :prerelease
  • :security_policy
  • :wrappers

For more information about these options, see the RubyGems documentation: http://rubygems.rubyforge.org/rubygems-update/Gem/DependencyInstaller.html.

Example
gem_package 'bundler' do
  options(:prerelease => true, :format_executable => false)
end

Specify with String

When using an explicit gem_binary, options must be passed as a string. When not using an explicit gem_binary, Chef Infra Client is forced to spawn a gems process to install the gems (which uses more system resources) when options are passed as a string. String options are passed verbatim to the gems command and should be specified just as if they were passed on a command line. For example, --prerelease for a pre-release gem. Example
gem_package 'nokogiri' do
  gem_binary('/opt/ree/bin/gem')
  options('--prerelease --no-format-executable')
end

Specify with .gemrc File

Options can be specified in a .gemrc file. By default the gem_package resource will use the Ruby interface to install gems which will ignore the .gemrc file. The gem_package resource can be forced to use the gems command instead (and to read the .gemrc file) by adding the gem_binary attribute to a code block.

A template named gemrc.erb is located in a cookbook’s /templates directory:

:sources:
- http://<%= node['gem_file']['host'] %>:<%= node['gem_file']['port'] %>/

A recipe can be built that does the following:

  • Builds a .gemrc file based on a gemrc.erb template
  • Runs a Gem.configuration command
  • Installs a package using the .gemrc file
template '/root/.gemrc' do
  source 'gemrc.erb'
  action :create
  notifies :run, 'ruby_block[refresh_gemrc]', :immediately
end

ruby_block 'refresh_gemrc' do
  action :nothing
  block do
    Gem.configuration = Gem::ConfigFile.new []
  end
end

gem_package 'di-ruby-lvm' do
  gem_binary '/opt/chef/embedded/bin/gem'
  action :install
end

Actions


The 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. (Debian platform only; for other platforms, use the :remove action.)
:reconfig
Reconfigure a package. This action requires a response file.
:remove
Remove a package.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The package resource has the following properties:

allow_downgrade
Ruby Type: true, false | Default Value: true

yum_package resource only. Downgrade a package to satisfy requested version requirements.

arch
Ruby Type: String, Array

yum_package resource only. The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name.

default_release
Ruby Type: String

apt_package resource only. The default release. For example: stable.

flush_cache
Ruby Type: Array

Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Default value: [ :before, :after ]. The value may also be a Hash: ( { :before => true/false, :after => true/false } ).

Yum automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while the Chef Infra Client run is in-progress.

As an array:

yum_package 'some-package' do
  #...
  flush_cache [ :before ]
  #...
end

and as a Hash:

yum_package 'some-package' do
  #...
  flush_cache( { :after => true } )
  #...
end

Note

The flush_cache property does not flush the local Yum cache! Use Yum tools—yum clean headers, yum clean packages, yum clean all—to clean the local Yum cache.

gem_binary
Ruby Type: String

A property for the gem_package provider that is used to specify a gems binary.

homebrew_user
Ruby Type: String, Integer

homebrew_package resource only. The name of the Homebrew owner to be used by Chef Infra Client when executing a command.

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

options
Ruby Type: String

One (or more) additional options that are passed to the command.

package_name
Ruby Type: String, Array

The name of the package. Default value: the name of the resource block. See “Syntax” section above for more information.

response_file
Ruby Type: String

apt_package and dpkg_package resources only. The direct path to the file used to pre-seed a package.

response_file_variables
Ruby Type: Hash

apt_package and dpkg_package resources only. A Hash of response file variables in the form of {"VARIABLE" => "VALUE"}.

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

source
Ruby Type: String

Optional. The path to a package in the local file system.

Note

The AIX platform requires source to be a local file system path because installp does not retrieve packages using HTTP or FTP.

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

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 via a single HTTP transaction
  • Update or install multiple packages with a single resource during a Chef Infra Client run

For example, installing multiple packages:

package %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(package1 package2)  do
  action :nothing
end

log 'call a notification' do
  notifies :install, 'package[package1, package2]', :immediately
end

Note

Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the package_name or version properties.

Examples


The following examples demonstrate various approaches for using the package resource in recipes:

Install a gems file for use in recipes

chef_gem 'right_aws' do
  action :install
end

require 'right_aws'

Install a gems file from the local file system

gem_package 'right_aws' do
  source '/tmp/right_aws-1.11.0.gem'
  action :install
end

Install a package

package 'tar' do
  action :install
end

Install a package version

package 'tar' do
  version '1.16.1-1'
  action :install
end

Install a package with options

package 'debian-archive-keyring' do
  action :install
  options '--force-yes'
end

Install a package with a response_file

Use of a response_file is only supported on Debian and Ubuntu at this time. Custom resources must be written to support the use of a response_file, which contains debconf answers to questions normally asked by the package manager on installation. Put the file in /files/default of the cookbook where the package is specified and Chef Infra Client will use the cookbook_file resource to retrieve it.

To install a package with a response_file:

package 'sun-java6-jdk' do
  response_file 'java.seed'
end

Install a specified architecture using a named provider

yum_package 'glibc-devel' do
  arch 'i386'
end

Purge a package

package 'tar' do
  action :purge
end

Remove a package

package 'tar' do
  action :remove
end

Upgrade a package

package 'tar' do
  action :upgrade
end

Use the ignore_failure common attribute

gem_package 'syntax' do
  action :install
  ignore_failure true
end

Avoid unnecessary string interpolation

Do this:

package 'mysql-server' do
  version node['mysql']['version']
  action :install
end

and not this:

package 'mysql-server' do
  version "#{node['mysql']['version']}"
  action :install
end

Install a package in a platform

The following example shows how to use the package resource to install an application named app and ensure that the correct packages are installed for the correct platform:

package 'app_name' do
  action :install
end

case node[:platform]
when 'ubuntu','debian'
  package 'app_name-doc' do
    action :install
  end
when 'centos'
  package 'app_name-html' do
    action :install
  end
end

Install sudo, then configure /etc/sudoers/ file

The following example shows how to install sudo and then configure the /etc/sudoers file:

#  the following code sample comes from the ``default`` recipe in the ``sudo`` cookbook: https://github.com/chef-cookbooks/sudo

package 'sudo' do
  action :install
end

if node['authorization']['sudo']['include_sudoers_d']
  directory '/etc/sudoers.d' do
    mode        '0755'
    owner       'root'
    group       'root'
    action      :create
  end

  cookbook_file '/etc/sudoers.d/README' do
    source      'README'
    mode        '0440'
    owner       'root'
    group       'root'
    action      :create
  end
end

template '/etc/sudoers' do
  source 'sudoers.erb'
  mode '0440'
  owner 'root'
  group platform?('freebsd') ? 'wheel' : 'root'
  variables(
    :sudoers_groups => node['authorization']['sudo']['groups'],
    :sudoers_users => node['authorization']['sudo']['users'],
    :passwordless => node['authorization']['sudo']['passwordless']
  )
end

where

  • the package resource is used to install sudo
  • the if statement is used to ensure availability of the /etc/sudoers.d directory
  • the template resource tells Chef Infra Client where to find the sudoers template
  • the variables property is a hash that passes values to template files (that are located in the templates/ directory for the cookbook

Use a case statement to specify the platform

The following example shows how to use a case statement to tell Chef Infra Client which platforms and packages to install using cURL.

package 'curl'
  case node[:platform]
  when 'redhat', 'centos'
    package 'package_1'
    package 'package_2'
    package 'package_3'
  when 'ubuntu', 'debian'
    package 'package_a'
    package 'package_b'
    package 'package_c'
  end
end

where node[:platform] for each node is identified by Ohai during every Chef Infra Client run. For example:

package 'curl'
  case node[:platform]
  when 'redhat', 'centos'
    package 'zlib-devel'
    package 'openssl-devel'
    package 'libc6-dev'
  when 'ubuntu', 'debian'
    package 'openssl'
    package 'pkg-config'
    package 'subversion'
  end
end

Use symbols to reference attributes

Symbols may be used to reference attributes:

package 'mysql-server' do
  version node[:mysql][:version]
  action :install
end

instead of strings:

package 'mysql-server' do
  version node['mysql']['version']
  action :install
end

Use a whitespace array to simplify a recipe

The following examples show different ways of doing the same thing. The first shows a series of packages that will be upgraded:

package 'package-a' do
  action :upgrade
end

package 'package-b' do
  action :upgrade
end

package 'package-c' do
  action :upgrade
end

package 'package-d' do
  action :upgrade
end

and the next uses a single package resource and a whitespace array (%w):

package %w{package-a package-b package-c package-d} do
  action :upgrade
end

Specify the Homebrew user with a UUID

homebrew_package 'emacs' do
  homebrew_user 1001
end

Specify the Homebrew user with a string

homebrew_package 'vim' do
  homebrew_user 'user1'
end

pacman_package resource

pacman_package resource page

Use the pacman_package resource to manage packages (using pacman) on the Arch Linux platform.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, 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


A pacman_package resource block manages a package on a node, typically by installing it. The simplest use of the pacman_package resource is:

pacman_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the pacman_package resource is:

pacman_package 'name' do
  options           String
  package_name      String
  source            String
  timeout           String, Integer
  version           String, Array
  action            Symbol # defaults to :install if not specified
end

where:

  • pacman_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps 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 pacman_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.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The pacman_package resource has the following properties:

options
Ruby Type: String

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

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to:

  • Download the specified packages and versions via a single HTTP transaction
  • Update or install multiple packages with a single resource during a Chef Infra Client run

For example, installing multiple packages:

package %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(package1 package2)  do
  action :nothing
end

log 'call a notification' do
  notifies :install, 'package[package1, package2]', :immediately
end

Note

Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the package_name or version properties.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the pacman_package resource in recipes:

Install a package

pacman_package 'name of package' do
  action :install
end

paludis_package resource

paludis_package resource page

Use the paludis_package resource to manage packages for the Paludis platform.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, 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


A paludis_package resource block manages a package on a node, typically by installing it. The simplest use of the paludis_package resource is:

paludis_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the paludis_package resource is:

paludis_package 'name' do
  options           String
  package_name      String
  source            String
  timeout           Integer # default value: 3600
  version           String
  action            Symbol # defaults to :install if not specified
end

where:

  • paludis_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps 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 paludis_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.
:remove
Remove a package.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The paludis_package resource has the following properties:

options
Ruby Type: String

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

The optional path to a package on the local file system.

timeout
Ruby Type: Integer | Default Value: 3600

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the paludis_package resource in recipes:

Install a package

paludis_package 'name of package' do
  action :install
end

perl resource

perl resource page

Use the perl resource to execute scripts using the Perl interpreter. This resource may also use any of the actions and properties that are available to the execute resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Syntax


A perl resource block executes scripts Perl:

perl 'hello world' do
  code <<-EOH
    print "Hello world! From Chef and Perl.";
  EOH
end

where:

  • code specifies the command to run

The full syntax for all of the properties that are available to the perl resource is:

perl 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  notifies                   # see description
  path                       Array
  returns                    Integer, Array
  subscribes                 # see description
  timeout                    Integer, Float
  user                       String, Integer
  umask                      String, Integer
  action                     Symbol # defaults to :run if not specified
end

where:

  • perl is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • code, creates, cwd, environment, flags, group, path, returns, timeout, user, and umask are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The perl resource has the following actions:

:nothing
Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it.
:run
Default. Run a script.

Properties


The perl resource has the following properties:

code
Ruby Type: String

A quoted (” “) string of code to be executed.

creates
Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd
Ruby Type: String

The current working directory.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags
Ruby Type: String

One or more command line flags that are passed to the interpreter when a command is invoked.

group
Ruby Type: String, Integer

The group name or group ID that must be changed before running a command.

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns
Ruby Type: Integer, Array | Default Value: 0

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match.

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

timeout
Ruby Type: Integer, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

user
Ruby Type: String, Integer

The user name or user ID that should be changed before running a command.

umask
Ruby Type: String, Integer

The file mode creation mask, or umask.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

plist resource

plist resource page

Use the plist resource to set config values in plist files on macOS systems.

New in Chef Infra Client 16.0.

Syntax


The full syntax for all of the properties that are available to the plist resource is:

plist 'name' do
  encoding      String # default value: "binary"
  entry         String
  group         String # default value: "wheel"
  mode          String, Integer
  owner         String # default value: "root"
  path          String # default value: 'name' unless specified
  value         true, false, String, Integer, Float, Hash
  action        Symbol # defaults to :set if not specified
end

where:

  • plist 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.
  • encoding, entry, group, mode, owner, path, and value are the properties available to this resource.

Actions


The plist 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

Properties


The plist resource has the following properties:

encoding
Ruby Type: String | Default Value: binary

entry
Ruby Type: String

group
Ruby Type: String | Default Value: wheel

The group of the plist file.

mode
Ruby Type: String, Integer

The file mode of the plist file. Ex: ‘644’

owner
Ruby Type: String | Default Value: root

The owner of the plist file.

path
Ruby Type: String | Default Value: The resource block's name

The path on disk to the plist file.

value
Ruby Type: true, false, String, Integer, Float, Hash


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the plist resource in recipes:

Show hidden files in finder:

plist 'show hidden files' do
  path '/Users/vagrant/Library/Preferences/com.apple.finder.plist'
  entry 'AppleShowAllFiles'
  value true
end

portage_package resource

portage_package resource page

Use the portage_package resource to manage packages for the Gentoo platform.

Note

In many cases, it is better to use the package resource instead of this one. This is because when the package resource is used in a recipe, 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


A portage_package resource block manages a package on a node, typically by installing it. The simplest use of the portage_package resource is:

portage_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The portage_package resource has the following syntax:

portage_package 'name' do
  options           String, Array
  package_name      String, Array
  source            String
  timeout           String, Integer # default value: 3600
  version           String, Array
  action            Symbol # defaults to :install if not specified
end

where:

  • portage_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps 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 portage_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
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.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The portage_package resource has the following properties:

options
Ruby Type: String

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer | Default Value: 3600

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the portage_package resource in recipes:

Install a package

portage_package 'name of package' do
  action :install
end

powershell_package resource

powershell_package resource page

Use the powershell_package resource to install and manage packages via the PowerShell Package Manager for the Microsoft Windows platform. The powershell_package resource requires administrative access, and a source must be configured in the PowerShell Package Manager via the Register-PackageSource command or the powershell_package_source resource.

New in Chef Infra Client 12.16.

Syntax


A powershell_package resource block manages a package on a node, typically by installing it. The simplest use of the powershell_package resource is:

powershell_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The powershell_package resource has the following syntax:

powershell_package 'name' do
  options                   String, Array
  package_name              String, Array
  skip_publisher_check      true, false # default value: false
  source                    String
  timeout                   String, Integer
  version                   String, Array
  action                    Symbol # defaults to :install if not specified
end

where:

  • powershell_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • options, package_name, skip_publisher_check, source, timeout, and version are the properties available to this resource.

Actions


The powershell_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:remove
Remove a package.

Properties


The powershell_package resource has the following properties:

options
Ruby Type: String, Array

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

The name of the package. Default value: the name of the resource block.

skip_publisher_check
Ruby Type: true, false | Default Value: false

Skip validating module author.

New in Chef Client 14.3

source
Ruby Type: String

Specify the source of the package.

New in Chef Client 14.0

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the powershell_package resource in recipes:

Install a specific version of a package:

powershell_package 'xCertificate' do
  action :install
  version '1.1.0.0'
end

Install multiple packages:

powershell_package 'Install Multiple Packages' do
  action :install
  package_name %w(xCertificate xNetworking)
end

Install a package from a custom source:

powershell_package 'xCertificate' do
  action :install
  source 'MyGallery'
end

Install multiple packages, and specify package versions:

powershell_package 'Install Multiple Packages' do
  action :install
  package_name %w(xCertificate xNetworking)
  version ['2.0.0.0', '2.12.0.0']
end

Install multiple packages, specifying the package version for one package but not the other:

powershell_package 'Install Multiple Packages' do
   action :install
   package_name %w(xCertificate xNetworking)
   version [nil, '2.12.0.0']
 end

In this example, the nil tells powershell_package to install the most up to date version of xCertificate that is available, while pinning xNetworking to version 2.12.0.0.

Remove a package:

powershell_package 'xCertificate' do
  action :remove
end

powershell_package_source resource

powershell_package_source resource page

Use the powershell_package_source resource to register a PowerShell package repository.

New in Chef Infra Client 14.3.

Syntax


The full syntax for all of the properties that are available to the powershell_package_source resource is:

powershell_package_source 'name' do
  provider_name                String # default value: "NuGet"
  publish_location             String
  script_publish_location      String
  script_source_location       String
  source_name                  String # default value: 'name' unless specified
  trusted                      true, false # default value: false
  url                          String
  action                       Symbol # defaults to :register if not specified
end

where:

  • powershell_package_source is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • provider_name, publish_location, script_publish_location, script_source_location, source_name, trusted, and url are the properties available to this resource.

Actions


The powershell_package_source 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.
:register
Default. Registers and updates the PowerShell package source.
:unregister
Unregisters the PowerShell package source.

Properties


The powershell_package_source resource has the following properties:

provider_name
Ruby Type: String | Default Value: NuGet
Allowed Values: "NuGet", "PowerShellGet", "Programs", "chocolatey", "msi", "msu", "psl"

The package management provider for the source.

publish_location
Ruby Type: String

The URL where modules will be published to for this source. Only valid if the provider is PowerShellGet.

script_publish_location
Ruby Type: String

The location where scripts will be published to for this source. Only valid if the provider is PowerShellGet.

script_source_location
Ruby Type: String

The URL where scripts are located for this source. Only valid if the provider is PowerShellGet.

source_name
Ruby Type: String | Default Value: The resource block's name

The name of the package source.

trusted
Ruby Type: true, false | Default Value: false

Whether or not to trust packages from this source.

url
Ruby Type: String | REQUIRED

The url to the package source.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

powershell_script resource

powershell_script resource page

Use the powershell_script resource to execute a script using the Windows PowerShell interpreter, much like how the script and script-based resources—bash, csh, perl, python, and ruby—are used. The powershell_script is specific to the Microsoft Windows platform and the Windows PowerShell interpreter.

The powershell_script resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Syntax


A powershell_script resource block executes a batch script using the Windows PowerShell interpreter. For example, writing to an interpolated path:

powershell_script 'write-to-interpolated-path' do
  code <<-EOH
  $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt"
  $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.")
  $stream.close()
  EOH
end

The full syntax for all of the properties that are available to the powershell_script resource is:

powershell_script 'name' do
  architecture               Symbol
  code                       String
  command                    String, Array
  convert_boolean_return     true, false
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  guard_interpreter          Symbol
  interpreter                String
  returns                    Integer, Array
  timeout                    Integer, Float
  user                       String
  password                   String
  domain                     String
  action                     Symbol # defaults to :run if not specified
  elevated                   true, false
end

where:

  • powershell_script is the resource.
  • name is the name given to the resource block.
  • command is the command to be run and cwd is the location from which the command is run.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • architecture, code, command, convert_boolean_return, creates, cwd, environment, flags, group, guard_interpreter, interpreter, returns, sensitive, timeout, user, password, domain and elevated are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The powershell_script resource has the following actions:

:nothing
Inherited from execute resource. Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it.
:run
Default. Run the script.

Properties


The powershell_script 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

An optional property to set the command to be executed if it differs from the resource block’s name.

convert_boolean_return
Ruby Type: true, false | Default Value: false

Return 0 if the last line of a command is evaluated to be true or to return 1 if the last line is evaluated to be false.

When the guard_interpreter common attribute is set to :powershell_script, a string command will be evaluated as if this value were set to true. This is because the behavior of this attribute is similar to the value of the "$?" expression common in UNIX interpreters. For example, this:

powershell_script 'make_safe_backup' do
  guard_interpreter :powershell_script
  code 'cp ~/data/nodes.json ~/data/nodes.bak'
  not_if 'test-path ~/data/nodes.bak'
end

is similar to:

bash 'make_safe_backup' do
  code 'cp ~/data/nodes.json ~/data/nodes.bak'
  not_if 'test -e ~/data/nodes.bak'
end

creates
Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd
Ruby Type: String

The current working directory from which the command will be run.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({‘ENV_VARIABLE’ => ‘VALUE’}).

flags
Ruby Type: String

A string that is passed to the Windows PowerShell command. Default value (Windows PowerShell 3.0+): -NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Bypass, -InputFormat None.

group
Ruby Type: String, Integer

The group name or group ID that must be changed before running a command.

guard_interpreter
Ruby Type: Symbol | Default Value: :powershell_script

When this property is set to :powershell_script, the 64-bit version of the Windows PowerShell shell will be used to evaluate strings values for the not_if and only_if properties. Set this value to :default to use the 32-bit version of the cmd.exe shell.

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

Inherited from execute resource. The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match.

timeout
Ruby Type: Integer, Float

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. domain\user or user@my.dns.domain.com via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified.

password
Ruby Type: String

Windows only: The password of the user specified by the user property. Default value: nil. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified.

domain
Ruby Type: String

Windows only: The domain of the user specified by the user property. Default value: nil. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef 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.

elevated
Ruby Type: true, false

Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) interactively blocking the process.

This will cause the process to be run under a batch login instead of an interactive login. The user running Chef needs the “Replace a process level token” and “Adjust Memory Quotas for a process” permissions. The user that is running the command needs the “Log on as a batch job” permission.

Because this requires a login, the user and password properties are required.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the powershell_script resource in recipes:

Write to an interpolated path

powershell_script 'write-to-interpolated-path' do
  code <<-EOH
  $stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt"
  $stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.")
  $stream.close()
  EOH
end

Change the working directory

powershell_script 'cwd-then-write' do
  cwd Chef::Config[:file_cache_path]
  code <<-EOH
  $stream = [System.IO.StreamWriter] "C:/powershell-test2.txt"
  $pwd = pwd
  $stream.WriteLine("This is the contents of: $pwd")
  $dirs = dir
  foreach ($dir in $dirs) {
    $stream.WriteLine($dir.fullname)
  }
  $stream.close()
  EOH
end

Change the working directory in Microsoft Windows

powershell_script 'cwd-to-win-env-var' do
  cwd '%TEMP%'
  code <<-EOH
  $stream = [System.IO.StreamWriter] "./temp-write-from-chef.txt"
  $stream.WriteLine("chef on windows rox yo!")
  $stream.close()
  EOH
end

Pass an environment variable to a script

powershell_script 'read-env-var' do
  cwd Chef::Config[:file_cache_path]
  environment ({'foo' => 'BAZ'})
  code <<-EOH
  $stream = [System.IO.StreamWriter] "./test-read-env-var.txt"
  $stream.WriteLine("FOO is $env:foo")
  $stream.close()
  EOH
end

Evaluate for true and/or false

Use the convert_boolean_return attribute to raise an exception when certain conditions are met. For example, the following fragments will run successfully without error:

powershell_script 'false' do
  code '$false'
end

and:

powershell_script 'true' do
  code '$true'
end

whereas the following will raise an exception:

powershell_script 'false' do
  convert_boolean_return true
  code '$false'
end

Use the flags attribute

powershell_script 'Install IIS' do
  code <<-EOH
  Import-Module ServerManager
  Add-WindowsFeature Web-Server
  EOH
  flags '-NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Unrestricted, -InputFormat None, -File'
  guard_interpreter :powershell_script
  not_if '(Get-WindowsFeature -Name Web-Server).Installed'
end

Rename computer, join domain, reboot

The following example shows how to rename a computer, join a domain, and then reboot the computer:

reboot 'Restart Computer' do
  action :nothing
end

powershell_script 'Rename and Join Domain' do
  code <<-EOH
    ...your rename and domain join logic here...
  EOH
  not_if <<-EOH
    $ComputerSystem = gwmi win32_computersystem
    ($ComputerSystem.Name -like '#{node['some_attribute_that_has_the_new_name']}') -and
      $ComputerSystem.partofdomain)
  EOH
  notifies :reboot_now, 'reboot[Restart Computer]', :immediately
end

where:

  • The powershell_script resource block renames a computer, and then joins a domain
  • The reboot resource restarts the computer
  • The not_if guard prevents the Windows PowerShell script from running when the settings in the not_if guard match the desired state
  • The notifies statement tells the reboot resource block to run if the powershell_script block was executed during a Chef Infra Client run

Run a command as an alternate user

Note: When Chef is running as a service, this feature requires that the user that Chef runs as has ‘SeAssignPrimaryTokenPrivilege’ (aka ‘SE_ASSIGNPRIMARYTOKEN_NAME’) user right. By default only LocalSystem and NetworkService have this right when running as a service. This is necessary even if the user is an Administrator.

This right can be added and checked in a recipe using this example:

# Add 'SeAssignPrimaryTokenPrivilege' for the user
Chef::ReservedNames::Win32::Security.add_account_right('<user>', 'SeAssignPrimaryTokenPrivilege')

# Check if the user has 'SeAssignPrimaryTokenPrivilege' rights
Chef::ReservedNames::Win32::Security.get_account_right('<user>').include?('SeAssignPrimaryTokenPrivilege')

The following example shows how to run mkdir test_dir from a Chef Infra Client run as an alternate user.

# Passing only username and password
powershell_script 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username"
 password "password"
end

# Passing username and domain
powershell_script 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 domain "domain"
 user "username"
 password "password"
end

# Passing username = 'domain-name\\username'. No domain is passed
powershell_script 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "domain-name\\username"
 password "password"
end

# Passing username = 'username@domain-name'. No domain is passed
powershell_script 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username@domain-name"
 password "password"
end

# Work around User Access Control (UAC)
powershell_script 'mkdir test_dir' do
 code "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username"
 password "password"
 elevated true
end

python resource

python resource page

Use the python resource to execute scripts using the Python interpreter. This resource may also use any of the actions and properties that are available to the execute resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Syntax


The python resource has the following syntax:

python 'hello world' do
  code <<-EOH
    print "Hello world! From Chef and Python."
  EOH
end

where:

  • code specifies the command to run

The full syntax for all of the properties that are available to the python resource is:

python 'name' do
  code             String
  command          String # 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
  interpreter      String
  live_stream      true, false # default value: false
  password         String
  returns          Integer, Array # default value: 0
  sensitive        true, false # default value: "True if the password property is set. False otherwise."
  timeout          Integer, Float
  umask            String, Integer
  user             String, Integer
  action           Symbol # defaults to :run if not specified
end

where:

  • python is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • code, command, creates, cwd, default_env, domain, elevated, environment, flags, group, interpreter, live_stream, password, returns, sensitive, timeout, umask, and user are the properties available to this resource.

Actions


The python resource has the following actions:

:nothing
Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it.
:run
Default. Run a script.

Properties


The python resource has the following properties:

code
Ruby Type: String | REQUIRED

A quoted (” “) string of code to be executed.

creates
Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd
Ruby Type: String

The current working directory from which the command will be run.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags
Ruby Type: String

One or more command line flags that are passed to the interpreter when a command is invoked.

group
Ruby Type: String, Integer

The group name or group ID that must be changed before running a command.

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

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).

returns
Ruby Type: Integer, Array | Default Value: 0

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match.

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

timeout
Ruby Type: Integer, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

user
Ruby Type: String, Integer

The user name or user ID that should be changed before running a command.

umask
Ruby Type: String, Integer

The file mode creation mask, or umask.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

reboot resource

reboot resource page

Use the reboot resource to reboot a node, a necessary step with some installations on certain platforms. This resource is supported for use on the Microsoft Windows, macOS, and Linux platforms. In using this resource via notifications, it’s important to only use immediate notifications. Delayed notifications produce unintuitive and probably undesired results.

New in Chef Infra Client 12.0.

Syntax


The full syntax for all of the properties that are available to the reboot resource is:

reboot 'name' do
  delay_mins      Integer # default value: 0
  reason          String # default value: "Reboot by Chef Infra Client"
  action          Symbol # defaults to :nothing if not specified
end

where:

  • reboot is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • delay_mins and reason are the properties available to this resource.

Actions


The reboot resource has the following actions:

:cancel
Cancel a reboot request.
:nothing
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.
:reboot_now
Reboot a node so that Chef Infra Client may continue the installation process.
:request_reboot
Reboot a node at the end of a Chef Infra Client run.

Properties


The reboot resource has the following properties:

delay_mins
Ruby Type: Integer | Default Value: 0

The amount of time (in minutes) to delay a reboot request.

reason
Ruby Type: String | Default Value: Reboot by Chef Infra Client

A string that describes the reboot action.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the reboot resource in recipes:

Reboot a node immediately

reboot 'now' do
  action :nothing
  reason 'Cannot continue Chef run without a reboot.'
  delay_mins 2
end

execute 'foo' do
  command '...'
  notifies :reboot_now, 'reboot[now]', :immediately
end

Reboot a node at the end of a Chef Infra Client run

reboot 'app_requires_reboot' do
  action :request_reboot
  reason 'Need to reboot when the run completes successfully.'
  delay_mins 5
end

Cancel a reboot

reboot 'cancel_reboot_request' do
  action :cancel
  reason 'Cancel a previous end-of-run reboot request.'
end

Rename computer, join domain, reboot

The following example shows how to rename a computer, join a domain, and then reboot the computer:

reboot 'Restart Computer' do
  action :nothing
end

powershell_script 'Rename and Join Domain' do
  code <<-EOH
    ...your rename and domain join logic here...
  EOH
  not_if <<-EOH
    $ComputerSystem = gwmi win32_computersystem
    ($ComputerSystem.Name -like '#{node['some_attribute_that_has_the_new_name']}') -and
      $ComputerSystem.partofdomain)
  EOH
  notifies :reboot_now, 'reboot[Restart Computer]', :immediately
end

where:

  • The powershell_script resource block renames a computer, and then joins a domain
  • The reboot resource restarts the computer
  • The not_if guard prevents the Windows PowerShell script from running when the settings in the not_if guard match the desired state
  • The notifies statement tells the reboot resource block to run if the powershell_script block was executed during a Chef Infra Client run

registry_key resource

registry_key resource page

Use the registry_key resource to create and delete registry keys in Microsoft Windows.

Note

64-bit versions of Microsoft Windows have a 32-bit compatibility layer in the registry that reflects and redirects certain keys (and their values) into specific locations (or logical views) of the registry hive.

Chef Infra Client can access any reflected or redirected registry key. The machine architecture of the system on which Chef Infra Client is running is used as the default (non-redirected) location. Access to the SysWow64 location is redirected must be specified. Typically, this is only necessary to ensure compatibility with 32-bit applications that are running on a 64-bit operating system.

32-bit versions of Chef Infra Client (12.8 and earlier) and 64-bit versions of Chef Infra Client (12.9 and later) generally behave the same in this situation, with one exception: it is only possible to read and write from a redirected registry location using chef-client version 12.9 (and later).

For more information, see: Registry Reflection.

Syntax


A registry_key resource block creates and deletes registry keys in Microsoft Windows:

registry_key 'HKEY_LOCAL_MACHINE\\...\\System' do
  values [{
    name: 'NewRegistryKeyValue',
    type: :multi_string,
    data: %w(foo bar baz),
  }]
  action :create
end

Use multiple registry key entries with key values that are based on node attributes:

registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\name_of_registry_key' do
  values [{name: 'key_name', type: :string, data: 'C:\Windows\System32\file_name.bmp'},
          {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']},
          {name: 'key_name', type: :string, data: node['node_name']['attribute']['value']}
         ]
  action :create
end

The registry_key resource has the following syntax:

registry_key 'name' do
  architecture      Symbol # default value: :machine
  key               String # default value: 'name' unless specified
  recursive         true, false # default value: false
  values
  action            Symbol # defaults to :create if not specified
end

where:

  • registry_key is the resource
  • name is the name of the resource block
  • values is a hash that contains at least one registry key to be created or deleted. Each registry key in the hash is grouped by brackets in which the name:, type:, and data: values for that registry key are specified.
  • type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD. {{< warning >}} :multi_string must be an array, even if there is only a single string. {{< /warning >}}
  • action identifies the steps Chef Infra Client will take to bring the node into the desired state
  • architecture, key, recursive and values are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Registry Key Path Separators

A Microsoft Windows registry key can be used as a string in Ruby code, such as when a registry key is used as the name of a recipe. In Ruby, when a registry key is enclosed in a double-quoted string (" "), the same backslash character (\) that is used to define the registry key path separator is also used in Ruby to define an escape character. Therefore, the registry key path separators must be escaped when they are enclosed in a double-quoted string. For example, the following registry key:

HKCU\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Themes

may be enclosed in a single-quoted string with a single backslash:

'HKCU\SOFTWARE\path\to\key\Themes'

or may be enclosed in a double-quoted string with an extra backslash as an escape character:

"HKCU\\SOFTWARE\\path\\to\\key\\Themes"

Recipe DSL Methods

Six methods are present in the Recipe DSL to help verify the registry during a Chef Infra Client run on the Microsoft Windows platform—registry_data_exists?, registry_get_subkeys, registry_get_values, registry_has_subkeys?, registry_key_exists?, and registry_value_exists?—these helpers ensure the powershell_script resource is idempotent.

registry_data_exists?

Use the registry_data_exists? method to find out if a Microsoft Windows registry key contains the specified data of the specified type under the value.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_data_exists? method is as follows:

registry_data_exists?(
  KEY_PATH,
  { name: 'NAME', type: TYPE, data: DATA },
  ARCHITECTURE
)

where:

  • KEY_PATH is the path to the registry key value. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • { name: 'NAME', type: TYPE, data: DATA } is a hash that contains the expected name, type, and data of the registry key value
  • type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. Set to :i386 to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to:x86_64 to force write to a 64-bit registry location, however Chef Infra Client returns an exception if :x86_64 is used on a 32-bit machine. Set to :machine to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: :machine.

This method will return true or false.

registry_get_subkeys

Use the registry_get_subkeys method to get a list of registry key values that are present for a Microsoft Windows registry key.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_get_subkeys method is as follows:

subkey_array = registry_get_subkeys(KEY_PATH, ARCHITECTURE)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. Set to :i386 to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to:x86_64 to force write to a 64-bit registry location, however Chef Infra Client returns an exception if :x86_64 is used on a 32-bit machine. Set to :machine to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: :machine.

This returns an array of registry key values.

registry_get_values

Use the registry_get_values method to get the registry key values (name, type, and data) for a Microsoft Windows registry key.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_get_values method is as follows:

subkey_array = registry_get_values(KEY_PATH, ARCHITECTURE)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. Set to :i386 to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to:x86_64 to force write to a 64-bit registry location, however Chef Infra Client returns an exception if :x86_64 is used on a 32-bit machine. Set to :machine to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: :machine.

This returns an array of registry key values.

registry_has_subkeys?

Use the registry_has_subkeys? method to find out if a Microsoft Windows registry key has one (or more) values.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_has_subkeys? method is as follows:

registry_has_subkeys?(KEY_PATH, ARCHITECTURE)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. Set to :i386 to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to:x86_64 to force write to a 64-bit registry location, however Chef Infra Client returns an exception if :x86_64 is used on a 32-bit machine. Set to :machine to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: :machine.

This method will return true or false.

registry_key_exists?

Use the registry_key_exists? method to find out if a Microsoft Windows registry key exists at the specified path.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_key_exists? method is as follows:

registry_key_exists?(KEY_PATH, ARCHITECTURE)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. Set to :i386 to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to:x86_64 to force write to a 64-bit registry location, however Chef Infra Client returns an exception if :x86_64 is used on a 32-bit machine. Set to :machine to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: :machine.

This method will return true or false. (Any registry key values that are associated with this registry key are ignored.)

registry_value_exists?

Use the registry_value_exists? method to find out if a registry key value exists. Use registry_data_exists? to test for the type and data of a registry key value.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_dvalue_exists? method is as follows:

registry_value_exists?(
  KEY_PATH,
  { name: 'NAME' },
  ARCHITECTURE
)

where:

  • KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
  • { name: 'NAME' } is a hash that contains the name of the registry key value; if either type: or :value are specified in the hash, they are ignored
  • type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.
  • ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. Set to :i386 to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows. Set to:x86_64 to force write to a 64-bit registry location, however Chef Infra Client returns an exception if :x86_64 is used on a 32-bit machine. Set to :machine to allow Chef Infra Client to allow Chef Infra Client to use the appropriate key location based on your node’s architecture. Default value: :machine.

This method will return true or false.

Actions


The registry_key resource has the following actions:

:create
Default. Create a registry key. If a registry key already exists (but does not match), update that registry key to match.
:create_if_missing
Create a registry key if it does not exist. Also, create a registry key value if it does not exist.
:delete
Delete the specified values for a registry key.
:delete_key
Delete the specified registry key and all of its subkeys. The :delete_key action with the recursive attribute will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The registry_key resource has the following properties:

architecture
Ruby Type: Symbol | Default Value: :machine
Allowed Values: :i386, :machine, :x86_64

The architecture of the node for which keys are to be created or deleted. Possible values: :i386 (for nodes with a 32-bit registry), :x86_64 (for nodes with a 64-bit registry), and :machine (to have Chef Infra Client determine the architecture during a Chef Infra Client run).

In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because Chef Infra Client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, Chef Infra Client is able to access the registry key on the 32-bit machine).

key
Ruby Type: String | Default Value: The resource block's name

The path to the location in which a registry key is to be created or from which a registry key is to be deleted. Default value: the name of the resource block. See “Syntax” section above for more information. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.

recursive
Ruby Type: true, false | Default Value: false

When creating a key, this value specifies that the required keys for the specified path are to be created. When using the :delete_key action in a recipe, and if the registry key has subkeys, then set the value for this property to true. The :delete_key action with the recursive attribute will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client.

values
Ruby Type: Hash, Array

An array of hashes, where each Hash contains the values that are to be set under a registry key. Each Hash must contain name:, type:, and data: (and must contain no other key values).

type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.

Warning

:multi_string must be an array, even if there is only a single string.

Examples


The following examples demonstrate various approaches for using the registry_key resource in recipes:

Create a registry key

Use a double-quoted string:

registry_key "HKEY_LOCAL_MACHINE\\path-to-key\\Policies\\System" do
  values [{
    name: 'EnableLUA',
    type: :dword,
    data: 0
  }]
  action :create
end

or a single-quoted string:

registry_key 'HKEY_LOCAL_MACHINE\path-to-key\Policies\System' do
  values [{
    name: 'EnableLUA',
    type: :dword,
    data: 0
  }]
  action :create
end

Delete a registry key value

Use a double-quoted string:

registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\path\\to\\key\\AU" do
  values [{
    name: 'NoAutoRebootWithLoggedOnUsers',
    type: :dword,
    data: ''
    }]
  action :delete
end

or a single-quoted string:

registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\path\to\key\AU' do
  values [{
    name: 'NoAutoRebootWithLoggedOnUsers',
    type: :dword,
    data: ''
    }]
  action :delete
end

Note

If data: is not specified, you get an error: Missing data key in RegistryKey values hash

Delete a registry key and its subkeys, recursively

Use a double-quoted string:

registry_key "HKCU\\SOFTWARE\\Policies\\path\\to\\key\\Themes" do
  recursive true
  action :delete_key
end

or a single-quoted string:

registry_key 'HKCU\SOFTWARE\Policies\path\to\key\Themes' do
  recursive true
  action :delete_key
end

Note

Be careful when using the :delete_key action with the recursive attribute. This will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by Chef Infra Client.

Use re-directed keys

In 64-bit versions of Microsoft Windows, HKEY_LOCAL_MACHINE\SOFTWARE\Example is a re-directed key. In the following examples, because HKEY_LOCAL_MACHINE\SOFTWARE\Example is a 32-bit key, the output will be “Found 32-bit key” if they are run on a version of Microsoft Windows that is 64-bit:

registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do
  architecture :i386
  recursive true
  action :create
end

or:

registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\Example" do
  architecture :x86_64
  recursive true
  action :delete_key
end

or:

ruby_block 'check 32-bit' do
  block do
    puts 'Found 32-bit key'
  end
  only_if {
    registry_key_exists?("HKEY_LOCAL_MACHINE\SOFTWARE\\Example",
    :i386)
  }
end

or:

ruby_block 'check 64-bit' do
  block do
    puts 'Found 64-bit key'
  end
  only_if {
    registry_key_exists?("HKEY_LOCAL_MACHINE\\SOFTWARE\\Example",
    :x86_64)
  }
end

Set proxy settings to be the same as those used by Chef Infra Client

Use a double-quoted string:

proxy = URI.parse(Chef::Config[:http_proxy])
registry_key 'HKCU\Software\Microsoft\path\to\key\Internet Settings' do
  values [{name: 'ProxyEnable', type: :reg_dword, data: 1},
          {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"},
          {name: 'ProxyOverride', type: :reg_string, data: <local>},
         ]
  action :create
end

or a single-quoted string:

proxy = URI.parse(Chef::Config[:http_proxy])
registry_key 'HKCU\Software\Microsoft\path\to\key\Internet Settings' do
  values [{name: 'ProxyEnable', type: :reg_dword, data: 1},
          {name: 'ProxyServer', data: "#{proxy.host}:#{proxy.port}"},
          {name: 'ProxyOverride', type: :reg_string, data: <local>},
         ]
  action :create
end

Set the name of a registry key to “(Default)"

Use a double-quoted string:

registry_key 'Set (Default) value' do
  key "HKLM\\Software\\Test\\Key\\Path"
  values [
    {name: '', type: :string, data: 'test'},
  ]
  action :create
end

or a single-quoted string:

registry_key 'Set (Default) value' do
  key 'HKLM\Software\Test\Key\Path'
  values [
    {name: '', type: :string, data: 'test'},
  ]
  action :create
end

where name: '' contains an empty string, which will set the name of the registry key to (Default).

remote_directory resource

remote_directory resource page

Use the remote_directory resource to incrementally transfer a directory from a cookbook to a node. The directory that is copied from the cookbook should be located under COOKBOOK_NAME/files/default/REMOTE_DIRECTORY. The remote_directory resource will obey file specificity.

Syntax


A remote_directory resource block transfers a directory from a cookbook to a node, and then assigns the permissions needed on that directory. For example:

remote_directory '/etc/apache2' do
  source 'apache2'
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

where:

  • '/etc/apache2' specifies the directory
  • source specifies a directory in the current cookbook (use the cookbook property to specify a file that is in a different cookbook)
  • owner, group, and mode define the permissions

The full syntax for all of the properties that are available to the remote_directory resource is:

remote_directory 'name' do
  cookbook                   String
  files_backup               Integer, false # default value: 5
  files_group                String, Integer
  files_mode                 String, Integer # default value: 0644 on *nix systems
  files_owner                String, Integer
  group                      String, Integer
  inherits                   true, false
  mode                       String, Integer
  overwrite                  true, false # default value: true
  owner                      String, Integer
  path                       String # default value: 'name' unless specified
  purge                      true, false
  recursive                  true, false
  rights                     Hash
  source                     String
  action                     Symbol # defaults to :create if not specified
end

where:

  • remote_directory is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • cookbook, files_backup, files_group, files_mode, files_owner, group, mode, overwrite, owner, path, purge, recursive, and source are the properties available to this resource.

Actions


The remote_directory resource has the following actions:

:create
Default. Create a directory and/or the contents of that directory. If a directory or its contents already exist (but does not match), update that directory or its contents to match.
:create_if_missing
Create a directory and/or the contents of that directory, but only if it does not exist.
:delete
Delete a directory, including the contents of that directory.
:nothing
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 remote_directory resource has the following properties:

cookbook
Ruby Type: String

The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook.

files_backup
Ruby Type: Integer, false | Default Value: 5

The number of backup copies to keep for files in the directory.

files_group
Ruby Type: String, Integer

Configure group permissions for files. A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

files_mode
Ruby Type: String, Integer | Default Value: 0644 on *nix systems

The octal mode for a file.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

files_owner
Ruby Type: String, Integer

Configure owner permissions for files. A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

group
Ruby Type: Integer, String

Use to configure permissions for directories. A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

inherits
Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

mode
Ruby Type: Integer, String

A quoted 3-5 character string that defines the octal mode. For example: '755', '0755', or 00755. If mode is not specified and if the directory already exists, the existing mode on the directory is used. If mode is not specified, the directory does not exist, and the :create action is specified, Chef Infra Client assumes a mask value of '0777', and then applies the umask for the system on which the directory is to be created to the mask value. For example, if the umask on a system is '022', Chef Infra Client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

overwrite
Ruby Type: true, false | Default Value: true

Overwrite a file when it is different.

owner
Ruby Type: Integer, String

Use to configure permissions for directories. A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path
Ruby Type: String | Default Value: The resource block's name

The path to the directory. Using a fully qualified path is recommended, but is not always required. Default value: the name of the resource block. See “Syntax” section above for more information.

purge
Ruby Type: true, false | Default Value: false

Purge extra files found in the target directory.

recursive
Ruby Type: true, false | Default Value: true

Create or delete directories recursively. Chef Infra Client must be able to create the directory structure, including parent directories (if missing), as defined in COOKBOOK_NAME/files/default/REMOTE_DIRECTORY.

rights
Ruby Type: Integer, String

Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options.

source
Ruby Type: String | Default Value: The base portion of the 'path' property.

The base name of the source file (and inferred from the path property). For example, in the default value, ‘/some/path/’ would be ‘path’.

Recursive Directories

The remote_directory resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the recursive attribute only applies group, mode, and owner attribute values to the remote directory itself and any inner directories the resource copies.

A directory structure:

/foo
  /bar
    /baz

The following example shows a way create a file in the /baz directory:

remote_directory "/foo/bar/baz" do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

But with this example, the group, mode, and owner attribute values will only be applied to /baz. Which is fine, if that’s what you want. But most of the time, when the entire /foo/bar/baz directory structure is not there, you must be explicit about each directory. For example:

%w[ /foo /foo/bar /foo/bar/baz ].each do |path|
  remote_directory path do
    owner 'root'
    group 'root'
    mode '0755'
  end
end

This approach will create the correct hierarchy—/foo, then /bar in /foo, and then /baz in /bar—and also with the correct attribute values for group, mode, and owner.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Recursive Directories

The remote_directory resource can be used to recursively create the path outside of remote directory structures, but the permissions of those outside paths are not managed. This is because the recursive attribute only applies group, mode, and owner attribute values to the remote directory itself and any inner directories the resource copies.

A directory structure:

/foo
  /bar
    /baz

The following example shows a way create a file in the /baz directory:

remote_directory "/foo/bar/baz" do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

But with this example, the group, mode, and owner attribute values will only be applied to /baz. Which is fine, if that’s what you want. But most of the time, when the entire /foo/bar/baz directory structure is not there, you must be explicit about each directory. For example:

%w[ /foo /foo/bar /foo/bar/baz ].each do |path|
  remote_directory path do
    owner 'root'
    group 'root'
    mode '0755'
  end
end

This approach will create the correct hierarchy—/foo, then /bar in /foo, and then /baz in /bar—and also with the correct attribute values for group, mode, and owner.

Example

This section contains a more detailed example of how Chef Infra Client manages recursive directory structures:

  • A cookbook named cumbria that is used to build a website
  • A subfolder in the /files/default directory named /website
  • A file named index.html, which is the root page for the website
  • Directories within /website named /cities, /places, and /football, which contains pages about cities, places, and football teams
  • A directory named /images, which contains images

These files are placed in the /files/default directory in the cumbria cookbook, like this:

cumbria
  /files
    /default
      /website
        index.html
        /cities
          carisle.html
          kendal.html
          penrith.html
          windermere.html
        /football
          carisle_united.html
        /images
          carisle_united.png
          furness_abbey.png
          hadrians_wall.png
          kendal.png
        /places
          furness_abbey.html
          hadrians_wall.html

The remote_directory resource can be used to build a website using these files. This website is being run on an Apache web server. The resource would be similar to the following:

remote_directory "/var/www/html" do
  files_mode '0440'
  files_owner 'yan'
  mode '0770'
  owner 'hamilton'
  source "website"
end

When Chef Infra Client runs, the remote_directory resource will tell Chef Infra Client to copy the directory tree from the cookbook to the file system using the structure defined in cookbook:

/var
  /www
    /html
      index.html
      /cities
        carisle.html
        kendal.html
        penrith.html
        windermere.html
      /football
        carisle_united.html
      /images
        carisle_united.png
        furness_abbey.png
        hadrians_wall.png
        kendal.png
      /places
        furness_abbey.html
        hadrians_wall.html

Chef Infra Client will manage the permissions of the entire directory structure below /html, for a total of 12 files and 4 directories. For example:

dr-xr-xr-x 2 root     root 4096 /var/www/html
dr--r----- 1 yan      root 4096 /var/www/html/index.html
drwxrwx--- 2 hamilton root 4096 /var/www/html/cities
dr--r----- 1 yan      root 4096 /var/www/html/cities/carlisle.html
dr--r----- 1 yan      root 4096 /var/www/html/cities/kendal.html
dr--r----- 1 yan      root 4096 /var/www/html/cities/penrith.html
dr--r----- 1 yan      root 4096 /var/www/html/cities/windermere.html
drwxrwx--- 2 hamilton root 4096 /var/www/html/football
dr--r----- 1 yan      root 4096 /var/www/html/football/carlisle_united.html
drwxrwx--- 2 hamilton root 4096 /var/www/html/images
dr--r----- 1 yan      root 4096 /var/www/html/images/carlisle_united/png
dr--r----- 1 yan      root 4096 /var/www/html/images/furness_abbey/png
dr--r----- 1 yan      root 4096 /var/www/html/images/hadrians_wall.png
dr--r----- 1 yan      root 4096 /var/www/html/images/kendal.png
drwxrwx--- 2 hamilton root 4096 /var/www/html/places
dr--r----- 1 yan      root 4096 /var/www/html/places/furness_abbey.html
dr--r----- 1 yan      root 4096 /var/www/html/places/hadrians_wall.html

Windows File Security

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.

Example

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

Examples


The following examples demonstrate various approaches for using the remote_directory resource in recipes:

Recursively transfer a directory from a remote location

# create up to 10 backups of the files
# set the files owner different from the directory
remote_directory '/tmp/remote_something' do
  source 'something'
  files_backup 10
  files_owner 'root'
  files_group 'root'
  files_mode '0644'
  owner 'nobody'
  group 'nobody'
  mode '0755'
end

Use with the chef_handler resource

The following example shows how to use the remote_directory resource and the chef_handler resource to reboot a handler named WindowsRebootHandler:

# the following code sample comes from the
# ``reboot_handler`` recipe in the ``windows`` cookbook:
# https://github.com/chef-cookbooks/windows

remote_directory node['chef_handler']['handler_path'] do
  source 'handlers'
  recursive true
  action :create
end

chef_handler 'WindowsRebootHandler' do
  source "#{node['chef_handler']['handler_path']}/windows_reboot_handler.rb"
  arguments node['windows']['allow_pending_reboots']
  supports :report => true, :exception => false
  action :enable
end

remote_file resource

remote_file resource page

Use the remote_file resource to transfer a file from a remote location using file specificity. This resource is similar to the file resource.

Note

Fetching files from the files/ directory in a cookbook should be done with the cookbook_file resource.

Syntax


A remote_file resource block manages files by using files that exist remotely. For example, to write the home page for an Apache website:

remote_file '/var/www/customers/public_html/index.html' do
  source 'http://somesite.com/index.html'
  owner 'web_admin'
  group 'web_admin'
  mode '0755'
  action :create
end

where:

  • '/var/www/customers/public_html/index.html' is path to the file to be created
  • 'http://somesite.com/index.html' specifies the location of the remote file, the file is downloaded from there
  • owner, group, and mode define the permissions

The full syntax for all of the properties that are available to the remote_file resource is:

remote_file 'name' do
  atomic_update              true, false
  authentication             # default value: remote
  backup                     Integer, false # default value: 5
  checksum                   String
  content                    String, nil
  diff                       String, nil
  force_unlink               true, false # default value: false
  ftp_active_mode            true, false # default value: false
  group                      String, Integer
  headers                    Hash
  inherits                   true, false
  manage_symlink_source      true, false
  mode                       String, Integer
  notifies                   # see description
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  rights                     Hash
  source                     String, Array
  subscribes                 # see description
  use_conditional_get        true, false
  verify                     String, Block
  remote_domain              String
  remote_password            String
  remote_user                String
  show_progress              true, false # default value: false
  use_etag                   true, false # default value: true
  use_last_modified          true, false # default value: true
  sensitive                  true, false # default value: false
  verifications              Array
  action                     Symbol # defaults to :create if not specified
end

where:

  • remote_file is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • atomic_update, authentication, backup, checksum, content, force_unlink, ftp_active_mode, group, headers, manage_symlink_source, mode, owner, path, remote_domain, remote_password, remote_user, show_progress, use_etag, use_last_modified, and verifications are the properties available to this resource.

Actions


The remote_file resource has the following actions:

:create
Default. Create a file. If a file already exists (but does not match), update that file to match.
:create_if_missing
Create a file only if the file does not exist. When the file exists, nothing happens.
:delete
Delete a file.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:touch
Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the file resource.)

Properties


The remote_file resource has the following properties:

atomic_update
Ruby Type: true, false | Default Value: False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.

Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides file_atomic_update, which is a global setting found in the client.rb file.

authentication
Ruby Type: Symbol | Default Value: :remote
Allowed Values: :local, :remote

backup
Ruby Type: Integer, false | Default Value: 5

The number of backups to be kept in /var/chef/backup (for UNIX- and Linux-based platforms) or C:/chef/backup (for the Microsoft Windows platform). Set to false to prevent backups from being kept.

checksum
Ruby Type: String

Optional, see use_conditional_get. The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, Chef Infra Client does not download it.

force_unlink
Ruby Type: true, false | Default Value: false

How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to true for Chef Infra Client to delete the non-file target and replace it with the specified file. Set to false for Chef Infra Client to raise an error.

ftp_active_mode
Ruby Type: true, false | Default Value: false

Whether Chef Infra Client uses active or passive FTP. Set to true to use active FTP.

group
Ruby Type: Integer, String

A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

headers
Ruby Type: Hash

A Hash of custom headers. For example:

headers({ "Cookie" => "user=grantmc; pass=p@ssw0rd!" })

or:

headers({ "Referer" => "#{header}" })

or:

headers( "Authorization"=>"Basic #{ Base64.encode64("#{username}:#{password}").gsub("\n", "") }" )

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

inherits
Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

manage_symlink_source
Ruby Type: true, false | Default Value: true

(with warning)

Change the behavior of the file resource if it is pointed at a symlink. When this value is set to true, the Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to false, Chef Infra Client will follow the symlink and will manage the permissions and content of the symlink’s target file.

The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning.

mode
Ruby Type: Integer, String

A quoted 3-5 character string that defines the octal mode. For example: '755', '0755', or 00755. If mode is not specified and if the file already exists, the existing mode on the file is used. If mode is not specified, the file does not exist, and the :create action is specified, Chef Infra Client assumes a mask value of '0777' and then applies the umask for the system on which the file is to be created to the mask value. For example, if the umask on a system is '022', Chef Infra Client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

owner
Ruby Type: Integer, String

A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path
Ruby Type: String | Default Value: The resource block's name

The full path to the file, including the file name and its extension. Default value: the name of the resource block. See “Syntax” section above for more information.

remote_user
Ruby Type: String

Windows only The name of a user with access to the remote file specified by the source property. The user name may optionally be specified with a domain, such as: domain\user or user@my.dns.domain.com via Universal Principal Name (UPN) format. The domain may also be set using the remote_domain property. Note that this property is ignored if source is not a UNC path. If this property is specified, the remote_password property is required.

New in Chef Client 13.4

remote_password
Ruby Type: String

Windows only The password of the user specified by the remote_user property. This property is required if remote_user is specified and may only be specified if remote_user is specified. The sensitive property for this resource will automatically be set to true if remote_password is specified.

New in Chef Client 13.4

remote_domain
Ruby Type: String

Windows only The domain of the user specified by the remote_user property. By default the resource will authenticate against the domain of the remote system, or as a local account if the remote system is not joined to a domain. If the remote system is not part of a domain, it is necessary to authenticate as a local user on the remote system by setting the domain to ., for example: remote_domain ".". The domain may also be specified as part of the remote_user property.

New in Chef Client 13.4

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

rights
Ruby Type: Integer, String

Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options.

source
Ruby Type: String, Array

Required. The location of the source file. The location of the source file may be HTTP (http://), FTP (ftp://), SFTP (sftp://), local (file:///), or UNC (\\host\share\file.tar.gz).

There are many ways to define the location of a source file. By using a path:

source 'http://couchdb.apache.org/img/sketch.png'

By using FTP:

source 'ftp://remote_host/path/to/img/sketch.png'

By using SFTP:

source 'sftp://username:password@remote_host:22/path/to/img/sketch.png'

By using a local path:

source 'file:///path/to/img/sketch.png'

By using a Microsoft Windows UNC:

source '\\\\path\\to\\img\\sketch.png'

By using a node attribute:

source node['nginx']['foo123']['url']

By using attributes to define paths:

source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2"

By defining multiple paths for multiple locations:

source 'http://seapower/spring.png', 'http://seapower/has_sprung.png'

By defining those same multiple paths as an array:

source ['http://seapower/spring.png', 'http://seapower/has_sprung.png']

When multiple paths are specified, Chef Infra Client will attempt to download the files in the order listed, stopping after the first successful download.

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

use_conditional_get
Ruby Type: true, false | Default Value: true

Enable conditional HTTP requests by using a conditional GET (with the If-Modified-Since header) or an opaque identifier (ETag). To use If-Modified-Since headers, use_last_modified must also be set to true. To use ETag headers, use_etag must also be set to true.

use_etag
Ruby Type: true, false | Default Value: true

Enable ETag headers. Set to false to disable ETag headers. To use this setting, use_conditional_get must also be set to true.

use_last_modified
Ruby Type: true, false | Default Value: true

Enable If-Modified-Since headers. Set to false to disable If-Modified-Since headers. To use this setting, use_conditional_get must also be set to true.

show_progess
Ruby Type: true, false | Default Value: false

Displays the progress of the file download. Set to true to enable this feature.

sensitive
Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef Infra Client.

verify
Ruby Type: String, Block

A block or a string that returns true or false. A string, when true is executed as a system command.

A block is arbitrary Ruby defined within the resource block by using the verify property. When a block is true, Chef Infra Client will continue to update the file as appropriate.

For example, this should return true:

remote_file '/tmp/baz' do
  verify { 1 == 1 }
end

This should return true:

remote_file '/etc/nginx.conf' do
  verify 'nginx -t -c %{path}'
end

This should return true:

remote_file '/tmp/bar' do
  verify { 1 == 1}
end

And this should return true:

remote_file '/tmp/foo' do
  verify do |path|
    true
  end
end

Whereas, this should return false:

remote_file '/tmp/turtle' do
  verify '/usr/bin/false'
end

If a string or a block return false, the Chef Infra Client run will stop and an error is returned.

Atomic File Updates

Atomic updates are used with file-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out.

Atomic updates are enabled by default. They can be managed globally using the file_atomic_update setting in the client.rb file. They can be managed on a per-resource basis using the atomic_update property that is available with the cookbook_file, file, remote_file, and template resources.

Note

On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the restorecon command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected.

Windows File Security

To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes. Access Control Lists (ACLs)

The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the rights property is as follows:

rights permission, principal, option_type => value

where

permission

Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control.

These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read.

(For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.)

principal

Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the SDDL string constants. Chef Infra Client does not need to know if a principal is a user or a group.

option_type

A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types:

Option TypeDescription
:applies_to_childrenSpecify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).
:applies_to_selfIndicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.
:one_level_deepIndicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, 'S-1-1-0'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
end

or:

rights :read, ['Administrators','Everyone']
rights :full_control, 'Users', :applies_to_children => true
rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true

Some other important things to know when using the rights attribute:

  • Only inherited rights remain. All existing explicit rights on the object are removed and replaced.
  • If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified.
  • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration.

Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
  deny_rights :read, ['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.

Prevent Re-downloads

To prevent Chef Infra Client from re-downloading files that are already present on a node, use one of the following attributes in a recipe: use_conditional_get (default) or checksum.

  • The use_conditional_get attribute is the default behavior of Chef Infra Client. If the remote file is located on a server that supports ETag and/or If-Modified-Since headers, Chef Infra Client will use a conditional GET to determine if the file has been updated. If the file has been updated, Chef Infra Client will re-download the file.
  • The checksum attribute will ask Chef Infra Client to compare the checksum for the local file to the one at the remote location. If they match, Chef Infra Client will not re-download the file. Using a local checksum for comparison requires that the local checksum be the correct checksum.

The desired approach just depends on the desired workflow. For example, if a node requires a new file every day, using the checksum approach would require that the local checksum be updated and/or verified every day as well, in order to ensure that the local checksum was the correct one. Using a conditional GET in this scenario will greatly simplify the management required to ensure files are being updated accurately.

Access a remote UNC path on Windows

The remote_file resource on Windows supports accessing files from a remote SMB/CIFS share. The file name should be specified in the source property as a UNC path e.g. \\myserver\myshare\mydirectory\myfile.txt. This allows access to the file at that path location even if the Chef Infra Client process identity does not have permission to access the file. Credentials for authenticating to the remote system can be specified using the remote_user, remote_domain, and remote_password properties when the user that Chef Infra Client is running does not have access to the remote file. See the “Properties” section for more details on these options.

Note: This is primarily for accessing remote files when the user that Chef Infra Client is running as does not have sufficient access, and alternative credentials need to be specified. If the user already has access, the credentials do not need to be specified. In a case where the local system and remote system are in the same domain, the remote_user and remote_password properties often do not need to be specified, as the user may already have access to the remote file share.

Examples:

Access a file from a different domain account:

remote_file "E:/domain_test.txt"  do
  source  "\\\\myserver\\myshare\\mydirectory\\myfile.txt"
  remote_domain "domain"
  remote_user "username"
  remote_password "password"
end

OR

remote_file "E:/domain_test.txt"  do
  source  "\\\\myserver\\myshare\\mydirectory\\myfile.txt"
  remote_user "domain\\username"
  remote_password "password"
end

Access a file using a local account on the remote machine:

remote_file "E:/domain_test.txt"  do
  source  "\\\\myserver\\myshare\\mydirectory\\myfile.txt"
  remote_domain "."
  remote_user "username"
  remote_password "password"
end

OR

remote_file "E:/domain_test.txt"  do
  source  "\\\\myserver\\myshare\\mydirectory\\myfile.txt"
  remote_user ".\\username"
  remote_password "password"
end

Examples


The following examples demonstrate various approaches for using the remote_file resource in recipes:

Transfer a file from a URL

remote_file '/tmp/testfile' do
  source 'http://www.example.com/tempfiles/testfile'
  mode '0755'
  checksum '3a7dac00b1' # A SHA256 (or portion thereof) of the file.
end

Transfer a file only when the source has changed

remote_file '/tmp/couch.png' do
  source 'http://couchdb.apache.org/img/sketch.png'
  action :nothing
end

http_request 'HEAD http://couchdb.apache.org/img/sketch.png' do
  message ''
  url 'http://couchdb.apache.org/img/sketch.png'
  action :head
  if ::File.exist?('/tmp/couch.png')
    headers 'If-Modified-Since' => File.mtime('/tmp/couch.png').httpdate
  end
  notifies :create, 'remote_file[/tmp/couch.png]', :immediately
end

Install a file from a remote location using bash

The following is an example of how to install the foo123 module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following:

  • Declares three variables
  • Gets the Nginx file from a remote location
  • Installs the file using Bash to the path specified by the src_filepath variable
# the following code sample is similar to the ``upload_progress_module``
# recipe in the ``nginx`` cookbook:
# https://github.com/chef-cookbooks/nginx

src_filename = "foo123-nginx-module-v#{
  node['nginx']['foo123']['version']
}.tar.gz"
src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}"
extract_path = "#{
  Chef::Config['file_cache_path']
  }/nginx_foo123_module/#{
  node['nginx']['foo123']['checksum']
}"

remote_file 'src_filepath' do
  source node['nginx']['foo123']['url']
  checksum node['nginx']['foo123']['checksum']
  owner 'root'
  group 'root'
  mode '0755'
end

bash 'extract_module' do
  cwd ::File.dirname(src_filepath)
  code <<-EOH
    mkdir -p #{extract_path}
    tar xzf #{src_filename} -C #{extract_path}
    mv #{extract_path}/*/* #{extract_path}/
    EOH
  not_if { ::File.exist?(extract_path) }
end

Store certain settings

The following recipe shows how an attributes file can be used to store certain settings. An attributes file is located in the attributes/ directory in the same cookbook as the recipe which calls the attributes file. In this example, the attributes file specifies certain settings for Python that are then used across all nodes against which this recipe will run.

Python packages have versions, installation directories, URLs, and checksum files. An attributes file that exists to support this type of recipe would include settings like the following:

default['python']['version'] = '2.7.1'

if python['install_method'] == 'package'
  default['python']['prefix_dir'] = '/usr'
else
  default['python']['prefix_dir'] = '/usr/local'
end

default['python']['url'] = 'http://www.python.org/ftp/python'
default['python']['checksum'] = '80e387...85fd61'

and then the methods in the recipe may refer to these values. A recipe that is used to install Python will need to do the following:

  • Identify each package to be installed (implied in this example, not shown)
  • Define variables for the package version and the install_path
  • Get the package from a remote location, but only if the package does not already exist on the target system
  • Use the bash resource to install the package on the node, but only when the package is not already installed
#  the following code sample comes from the ``oc-nginx`` cookbook on |github|: https://github.com/cookbooks/oc-nginx

version = node['python']['version']
install_path = "#{node['python']['prefix_dir']}/lib/python#{version.split(/(^\d+\.\d+)/)[1]}"

remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do
  source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2"
  checksum node['python']['checksum']
  mode '0755'
  not_if { ::File.exist?(install_path) }
end

bash 'build-and-install-python' do
  cwd Chef::Config[:file_cache_path]
  code <<-EOF
    tar -jxvf Python-#{version}.tar.bz2
    (cd Python-#{version} && ./configure #{configure_options})
    (cd Python-#{version} && make && make install)
  EOF
  not_if { ::File.exist?(install_path) }
end

Use the platform_family? method

The following is an example of using the platform_family? method in the Recipe DSL to create a variable that can be used with other resources in the same recipe. In this example, platform_family? is being used to ensure that a specific binary is used for a specific platform before using the remote_file resource to download a file from a remote location, and then using the execute resource to install that file by running a command.

if platform_family?('rhel')
  pip_binary = '/usr/bin/pip'
else
  pip_binary = '/usr/local/bin/pip'
end

remote_file "#{Chef::Config[:file_cache_path]}/distribute_setup.py" do
  source 'http://python-distribute.org/distribute_setup.py'
  mode '0755'
  not_if { File.exist?(pip_binary) }
end

execute 'install-pip' do
  cwd Chef::Config[:file_cache_path]
  command <<-EOF
    # command for installing Python goes here
    EOF
  not_if { File.exist?(pip_binary) }
end

where a command for installing Python might look something like:

#{node['python']['binary']} distribute_setup.py
#{::File.dirname(pip_binary)}/easy_install pip

Specify local Windows file path as a valid URI

When specifying a local Microsoft Windows file path as a valid file URI, an additional forward slash (/) is required. For example:

remote_file 'file:///c:/path/to/file' do
  ...       # other attributes
end

rhsm_errata resource

rhsm_errata resource page

Use the rhsm_errata resource to install packages associated with a given Red Hat Subscription Manager Errata ID. This is helpful if packages to mitigate a single vulnerability must be installed on your hosts.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the rhsm_errata resource is:

rhsm_errata 'name' do
  errata_id      String # default value: 'name' unless specified
  action         Symbol # defaults to :install if not specified
end

where:

  • rhsm_errata 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.
  • errata_id is the property available to this resource.

Actions


The rhsm_errata resource has the following actions:

:install
Default. Install a package for a specific errata ID.
: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 rhsm_errata resource has the following properties:

errata_id
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the errata ID if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the rhsm_errata resource in recipes:

Install a package from an Errata ID

rhsm_errata 'RHSA:2018-1234'

Specify an Errata ID that differs from the resource name

rhsm_errata 'errata-install'
  errata_id 'RHSA:2018-1234'
end

rhsm_errata_level resource

rhsm_errata_level resource page

Use the rhsm_errata_level resource to install all packages of a specified errata level from the Red Hat Subscription Manager. For example, you can ensure that all packages associated with errata marked at a ‘Critical’ security level are installed.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the rhsm_errata_level resource is:

rhsm_errata_level 'name' do
  errata_level      String # default value: 'name' unless specified
  action            Symbol # defaults to :install if not specified
end

where:

  • rhsm_errata_level 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.
  • errata_level is the property available to this resource.

Actions


The rhsm_errata_level resource has the following actions:

:install
Default. Install all packages of the specified errata level.
:nothing
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 rhsm_errata_level resource has the following properties:

errata_level
Ruby Type: String | Default Value: The resource block's name
Allowed Values: "critical", "important", "low", "moderate"

An optional property for specifying the errata level of packages to install if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the rhsm_errata_level resource in recipes:

Specify an errata level that differs from the resource name

rhsm_errata_level 'example_install_moderate' do
  errata_level 'moderate'
end

rhsm_register resource

rhsm_register resource page

Use the rhsm_register resource to register a node with the Red Hat Subscription Manager or a local Red Hat Satellite server.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the rhsm_register resource is:

rhsm_register 'name' do
  activation_key             String, Array
  auto_attach                true, false # default value: false
  environment                String
  force                      true, false # default value: false
  https_for_ca_consumer      true, false # default value: false
  install_katello_agent      true, false # default value: true
  organization               String
  password                   String
  satellite_host             String
  username                   String
  action                     Symbol # defaults to :register if not specified
end

where:

  • rhsm_register is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • activation_key, auto_attach, environment, force, https_for_ca_consumer, install_katello_agent, organization, password, satellite_host, and username are the properties available to this resource.

Actions


The rhsm_register 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.
:register
Default. Register the node with RHSM.
:unregister
Unregister the node from RHSM.

Properties


The rhsm_register resource has the following properties:

activation_key
Ruby Type: String, Array

A string or array of activation keys to use when registering; you must also specify the ‘organization’ property when using this property.

auto_attach
Ruby Type: true, false | Default Value: false

If true, RHSM will attempt to automatically attach the host to applicable subscriptions. It is generally better to use an activation key with the subscriptions pre-defined.

environment
Ruby Type: String

The environment to use when registering; required when using the username and password properties.

force
Ruby Type: true, false | Default Value: false

If true, the system will be registered even if it is already registered. Normally, any register operations will fail if the machine has already been registered.

https_for_ca_consumer
Ruby Type: true, false | Default Value: false

If true, Chef Infra Client will fetch the katello-ca-consumer-latest.noarch.rpm from the satellite_host using HTTPS.

New in Chef Infra Client 15.9

install_katello_agent
Ruby Type: true, false | Default Value: true

If true, the ‘katello-agent’ RPM will be installed.

organization
Ruby Type: String

The organization to use when registering; required when using the ‘activation_key’ property.

password
Ruby Type: String

The password to use when registering. This property is not applicable if using an activation key. If specified, username and environment are also required.

satellite_host
Ruby Type: String

The FQDN of the Satellite host to register with. If this property is not specified, the host will register with Red Hat’s public RHSM service.

username
Ruby Type: String

The username to use when registering. This property is not applicable if using an activation key. If specified, password and environment properties are also required.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the rhsm_register resource in recipes:

Register a node with RHSM

rhsm_register 'myhost' do
  activation_key 'ABCD1234'
  organization 'my_org'
end

rhsm_repo resource

rhsm_repo resource page

Use the rhsm_repo resource to enable or disable Red Hat Subscription Manager repositories that are made available via attached subscriptions.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the rhsm_repo resource is:

rhsm_repo 'name' do
  repo_name      String # default value: 'name' unless specified
  action         Symbol # defaults to :enable if not specified
end

where:

  • rhsm_repo is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • repo_name is the property available to this resource.

Actions


The rhsm_repo resource has the following actions:

:disable
Disable an RHSM repository.
:enable
Default. Enable an RHSM repository.
: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 rhsm_repo resource has the following properties:

repo_name
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the repository name if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the rhsm_repo resource in recipes:

Enable an RHSM repository

rhsm_repo 'rhel-7-server-extras-rpms'

Disable an RHSM repository

rhsm_repo 'rhel-7-server-extras-rpms' do
  action :disable
end

rhsm_subscription resource

rhsm_subscription resource page

Use the rhsm_subscription resource to add or remove Red Hat Subscription Manager subscriptions from your host. This can be used when a host’s activation_key does not attach all necessary subscriptions to your host.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the rhsm_subscription resource is:

rhsm_subscription 'name' do
  pool_id      String # default value: 'name' unless specified
  action       Symbol # defaults to :attach if not specified
end

where:

  • rhsm_subscription is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • pool_id is the property available to this resource.

Actions


The rhsm_subscription resource has the following actions:

:attach
Default. Attach the node to a subscription pool.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove the node from a subscription pool.

Properties


The rhsm_subscription resource has the following properties:

pool_id
Ruby Type: String | Default Value: The resource block's name

An optional property for specifying the Pool ID if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

route resource

route resource page

Use the route resource to manage the system routing table in a Linux environment.

Syntax


A route resource block manages the system routing table in a Linux environment:

route '10.0.1.10/32' do
  gateway '10.0.0.20'
  device 'eth1'
end

The full syntax for all of the properties that are available to the route resource is:

route 'name' do
  comment         String
  device          String
  gateway         String
  metric          Integer
  netmask         String
  route_type      Symbol, String # default value: :host
  target          String # default value: 'name' unless specified
  action          Symbol # defaults to :add if not specified
end

where:

  • route 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.
  • comment, device, gateway, metric, netmask, route_type, and target are the properties available to this resource.

Actions


The route resource has the following actions:

:add
Default. Add a route.
:delete
Delete a route.
: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 route resource has the following properties:

comment
Ruby Type: String

Add a comment for the route.

New in Chef Client 14.0

device
Ruby Type: String

The network interface to which the route applies.

gateway
Ruby Type: String

The gateway for the route.

metric
Ruby Type: Integer

The route metric value.

netmask
Ruby Type: String

The decimal representation of the network mask. For example: 255.255.255.0.

route_type
Ruby Type: Symbol, String | Default Value: :host
Allowed Values: :host, :net

target
Ruby Type: String | Default Value: The resource block's name

The IP address of the target route.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

rpm_package resource

rpm_package resource page

Use the rpm_package resource to manage packages using the RPM Package Manager.

Syntax


The full syntax for all of the properties that are available to the rpm_package resource is:

rpm_package 'name' do
  allow_downgrade      true, false # default value: true
  options              String, Array
  package_name         String
  source               String
  timeout              String, Integer
  version              String
  action               Symbol # defaults to :install if not specified
end

where:

  • rpm_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.
  • allow_downgrade, options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The rpm_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.
:remove
Remove a package.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The rpm_package resource has the following properties:

allow_downgrade
Ruby Type: true, false | Default Value: true

Allow downgrading a package to satisfy requested version requirements.

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

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the rpm_package resource in recipes:

Install a package

rpm_package 'name of package' do
  action :install
end

ruby resource

ruby resource page

Use the ruby resource to execute scripts using the Ruby interpreter. This resource may also use any of the actions and properties that are available to the execute resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

Note

The ruby script resource (which is based on the script resource) is different from the ruby_block resource because Ruby code that is run with this resource is created as a temporary file and executed like other script resources, rather than run inline.

Syntax


A ruby resource block executes scripts using Ruby:

ruby 'hello world' do
  code <<-EOH
    puts "Hello world! From Chef and Ruby."
  EOH
end

where:

  • cwd specifies the directory from which the command is run
  • code specifies the command to run

The full syntax for all of the properties that are available to the ruby resource is:

ruby 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  path                       Array
  returns                    Integer, Array
  timeout                    Integer, Float
  user                       String, Integer
  umask                      String, Integer
  action                     Symbol # defaults to :run if not specified
end

where:

  • ruby is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • code, creates, cwd, environment, flags, group, path, returns, timeout, user, and umask are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The ruby resource has the following actions:

:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:run
Default. Run a script.

Properties


The ruby resource has the following properties:

code
Ruby Type: String

A quoted (” “) string of code to be executed.

creates
Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd
Ruby Type: String

The current working directory.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags
Ruby Type: String

One or more command line flags that are passed to the interpreter when a command is invoked.

group
Ruby Type: String, Integer

The group name or group ID that must be changed before running a command.

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

returns
Ruby Type: Integer, Array | Default Value: 0

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match.

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

timeout
Ruby Type: Integer, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

user
Ruby Type: String, Integer

The user name or user ID that should be changed before running a command.

umask
Ruby Type: String, Integer

The file mode creation mask, or umask.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

ruby_block resource

ruby_block resource page

Use the ruby_block resource to execute Ruby code during a Chef Infra Client run. Ruby code in the ruby_block resource is evaluated with other resources during convergence, whereas Ruby code outside of a ruby_block resource is evaluated before other resources, as the recipe is compiled.

Syntax


A ruby_block resource block executes a block of arbitrary Ruby code. For example, to reload the client.rb file during a Chef Infra Client run:

ruby_block 'reload_client_config' do
  block do
    Chef::Config.from_file("/etc/chef/client.rb")
  end
  action :run
end

The full syntax for all of the properties that are available to the ruby_block resource is:

ruby_block 'name' do
  block                      Block
  block_name                 String # defaults to 'name' if not specified
  action                     Symbol # defaults to :run if not specified
end

where:

  • ruby_block is the resource.
  • name is the name given to the resource block.
  • block is the block of Ruby code to be executed.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • block and block_name are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The ruby_block resource has the following actions:

:create
The same as :run.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:run
Default. Run a Ruby block.

Properties


The ruby_block resource has the following properties:

block
Ruby Type: Block

A block of Ruby code.

block_name
Ruby Type: String | Default Value: The resource block's name

The name of the Ruby block. Default value: the name of the resource block. See “Syntax” section above for more information.

ignore_failure
Ruby Type: true, false | Default Value: false

Continue running a recipe if a resource fails for any reason.

notifies
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

retries
Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay
Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

subscribes
Ruby Type: Symbol, Chef::Resource\[String\]

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Examples


The following examples demonstrate various approaches for using the ruby_block resource in recipes:

Re-read configuration data

ruby_block 'reload_client_config' do
  block do
    Chef::Config.from_file('/etc/chef/client.rb')
  end
  action :run
end

Install repositories from a file, trigger a command, and force the internal cache to reload

The following example shows how to install new Yum repositories from a file, where the installation of the repository triggers a creation of the Yum cache that forces the internal cache for Chef Infra Client to reload:

execute 'create-yum-cache' do
 command 'yum -q makecache'
 action :nothing
end

ruby_block 'reload-internal-yum-cache' do
  block do
    Chef::Provider::Package::Yum::YumCache.instance.reload
  end
  action :nothing
end

cookbook_file '/etc/yum.repos.d/custom.repo' do
  source 'custom'
  mode '0755'
  notifies :run, 'execute[create-yum-cache]', :immediately
  notifies :create, 'ruby_block[reload-internal-yum-cache]', :immediately
end

Use an if statement with the platform recipe DSL method

The following example shows how an if statement can be used with the platform? method in the Recipe DSL to run code specific to Microsoft Windows. The code is defined using the ruby_block resource:

# the following code sample comes from the ``client`` recipe
# in the following cookbook: https://github.com/chef-cookbooks/mysql

if platform?('windows')
  ruby_block 'copy libmysql.dll into ruby path' do
    block do
      require 'fileutils'
      FileUtils.cp "#{node['mysql']['client']['lib_dir']}\\libmysql.dll",
        node['mysql']['client']['ruby_dir']
    end
    not_if { File.exist?("#{node['mysql']['client']['ruby_dir']}\\libmysql.dll") }
  end
end

Stash a file in a data bag

The following example shows how to use the ruby_block resource to stash a BitTorrent file in a data bag so that it can be distributed to nodes in the organization.

# the following code sample comes from the ``seed`` recipe
# in the following cookbook: https://github.com/mattray/bittorrent-cookbook

ruby_block 'share the torrent file' do
  block do
    f = File.open(node['bittorrent']['torrent'],'rb')
    #read the .torrent file and base64 encode it
    enc = Base64.encode64(f.read)
    data = {
      'id'=>bittorrent_item_id(node['bittorrent']['file']),
      'seed'=>node.ipaddress,
      'torrent'=>enc
    }
    item = Chef::DataBagItem.new
    item.data_bag('bittorrent')
    item.raw_data = data
    item.save
  end
  action :nothing
  subscribes :create, "bittorrent_torrent[#{node['bittorrent']['torrent']}]", :immediately
end

Update the /etc/hosts file

The following example shows how the ruby_block resource can be used to update the /etc/hosts file:

# the following code sample comes from the ``ec2`` recipe
# in the following cookbook: https://github.com/chef-cookbooks/dynect

ruby_block 'edit etc hosts' do
  block do
    rc = Chef::Util::FileEdit.new('/etc/hosts')
    rc.search_file_replace_line(/^127\.0\.0\.1 localhost$/,
       '127.0.0.1 #{new_fqdn} #{new_hostname} localhost')
    rc.write_file
  end
end

Set environment variables

The following example shows how to use variables within a Ruby block to set environment variables using rbenv.

node.override[:rbenv][:root] = rbenv_root
node.override[:ruby_build][:bin_path] = rbenv_binary_path

ruby_block 'initialize' do
  block do
    ENV['RBENV_ROOT'] = node[:rbenv][:root]
    ENV['PATH'] = "#{node[:rbenv][:root]}/bin:#{node[:ruby_build][:bin_path]}:#{ENV['PATH']}"
  end
end

Set JAVA_HOME

The following example shows how to use a variable within a Ruby block to set the java_home environment variable:

ruby_block 'set-env-java-home' do
  block do
    ENV['JAVA_HOME'] = java_home
  end
end

Run specific blocks of Ruby code on specific platforms

The following example shows how the platform? method and an if statement can be used in a recipe along with the ruby_block resource to run certain blocks of Ruby code on certain platforms:

if platform_family?('debian', 'rhel', 'fedora', 'amazon')
  ruby_block 'update-java-alternatives' do
    block do
      if platform?('ubuntu', 'debian') and version == 6
        run_context = Chef::RunContext.new(node, {})
        r = Chef::Resource::Execute.new('update-java-alternatives', run_context)
        r.command 'update-java-alternatives -s java-6-openjdk'
        r.returns [0,2]
        r.run_action(:create)
      else

        require 'fileutils'
        arch = node['kernel']['machine'] =~ /x86_64/ ? 'x86_64' : 'i386'
        Chef::Log.debug("glob is #{java_home_parent}/java*#{version}*openjdk*")
        jdk_home = Dir.glob("#{java_home_parent}/java*#{version}*openjdk{,[-\.]#{arch}}")[0]
        Chef::Log.debug("jdk_home is #{jdk_home}")

        if File.exist? java_home
          FileUtils.rm_f java_home
        end
        FileUtils.ln_sf jdk_home, java_home

        cmd = Chef::ShellOut.new(
              %Q[ update-alternatives --install /usr/bin/java java #{java_home}/bin/java 1;
              update-alternatives --set java #{java_home}/bin/java ]
              ).run_command
           unless cmd.exitstatus == 0 or cmd.exitstatus == 2
          Chef::Application.fatal!('Failed to update-alternatives for openjdk!')
        end
      end
    end
    action :nothing
  end
end

Reload the configuration

The following example shows how to reload the configuration of a chef-client using the remote_file resource to:

  • using an if statement to check whether the plugins on a node are the latest versions
  • identify the location from which Ohai plugins are stored
  • using the notifies property and a ruby_block resource to trigger an update (if required) and to then reload the client.rb file.
directory 'node[:ohai][:plugin_path]' do
  owner 'chef'
  recursive true
end

ruby_block 'reload_config' do
  block do
    Chef::Config.from_file('/etc/chef/client.rb')
  end
  action :nothing
end

if node[:ohai].key?(:plugins)
  node[:ohai][:plugins].each do |plugin|
    remote_file node[:ohai][:plugin_path] +"/#{plugin}" do
      source plugin
      owner 'chef'
      notifies :run, 'ruby_block[reload_config]', :immediately
    end
  end
end

script resource

script resource page

Use the script resource to execute scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby. This resource may also use any of the actions and properties that are available to the execute resource. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

This resource is the base resource for several other resources used for scripting on specific platforms. For more information about specific resources for specific platforms, see the following topics:

Changed in 12.19 to support windows alternate user identity in execute resources

Syntax


A script resource block typically executes scripts using a specified interpreter, such as Bash, csh, Perl, Python, or Ruby:

script 'extract_module' do
  interpreter "bash"
  cwd ::File.dirname(src_filepath)
  code <<-EOH
    mkdir -p #{extract_path}
    tar xzf #{src_filename} -C #{extract_path}
    mv #{extract_path}/*/* #{extract_path}/
  EOH
  not_if { ::File.exist?(extract_path) }
end

where:

  • interpreter specifies the command shell to use
  • cwd specifies the directory from which the command is run
  • code specifies the command to run

    It is more common to use the script-based resource that is specific to the command shell. Chef has shell-specific resources for Bash, csh, ksh, Perl, Python, and Ruby.

    The same command as above, but run using the bash resource:

    bash 'extract_module' do
      cwd ::File.dirname(src_filepath)
      code <<-EOH
        mkdir -p #{extract_path}
        tar xzf #{src_filename} -C #{extract_path}
        mv #{extract_path}/*/* #{extract_path}/
      EOH
      not_if { ::File.exist?(extract_path) }
    end
    

The full syntax for all of the properties that are available to the script resource is:

script 'name' do
  code                       String
  creates                    String
  cwd                        String
  environment                Hash
  flags                      String
  group                      String, Integer
  interpreter                String
  path                       Array
  returns                    Integer, Array
  timeout                    Integer, Float
  user                       String
  password                   String
  domain                     String
  umask                      String, Integer
  action                     Symbol # defaults to :run if not specified
end

where:

  • script is the resource
  • name is the name of the resource block
  • cwd is the location from which the command is run
  • action identifies the steps Chef Infra Client will take to bring the node into the desired state
  • code, creates, cwd, environment, flags, group, interpreter, path, returns, timeout, user, password, domain and umask are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The script resource has the following actions:

:nothing
Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it.
:run
Default. Run a script.

Properties


The script resource has the following properties:

code
Ruby Type: String

A quoted (” “) string of code to be executed.

creates
Ruby Type: String

Prevent a command from creating a file when that file already exists.

cwd
Ruby Type: String

The current working directory from which the command will be run.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags
Ruby Type: String

One or more command line flags that are passed to the interpreter when a command is invoked.

group
Ruby Type: String, Integer

The group name or group ID that must be changed before running a command.

interpreter
Ruby Type: String

The script interpreter to use during code execution.

returns
Ruby Type: Integer, Array | Default Value: 0

The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match.

timeout
Ruby Type: Integer, Float | Default Value: 3600

The amount of time (in seconds) a command is to wait before timing out.

user
Ruby Type: String

The user name of the user identity with which to launch the new process. Default value: nil. The user name may optionally be specified with a domain, i.e. domainuser or user@my.dns.domain.com via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified.

password
Ruby Type: String

Windows only: The password of the user specified by the user property. Default value: nil. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified.

domain
Ruby Type: String

Windows only: The domain of the user user specified by the user property. Default value: nil. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property.

umask
Ruby Type: String, Integer

The file mode creation mask, or umask.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Guard Interpreter

Any resource that passes a string command may also specify the interpreter that will be used to evaluate that string command. This is done by using the guard_interpreter property to specify a script-based resource. Attributes

The guard_interpreter property may be set to any of the following values:

:bash

Evaluates a string command using the bash resource.

:batch

Evaluates a string command using the batch resource. Default value (within a batch resource block): :batch.

:csh

Evaluates a string command using the csh resource.

:default

Default. Executes the default interpreter as identified by 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.

Example

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

Examples


The following examples demonstrate various approaches for using the script resource in recipes:

Use a named provider to run a script

bash 'install_something' do
  user 'root'
  cwd '/tmp'
  code <<-EOH
    wget http://www.example.com/tarball.tar.gz
    tar -zxf tarball.tar.gz
    cd tarball
    ./configure
    make
    make   install
  EOH
end

Run a script

script 'install_something' do
  interpreter 'bash'
  user 'root'
  cwd '/tmp'
  code <<-EOH
    wget http://www.example.com/tarball.tar.gz
    tar -zxf tarball.tar.gz
    cd tarball
    ./configure
    make
    make install
  EOH
end

or something like:

bash 'openvpn-server-key' do
  environment('KEY_CN' => 'server')
  code <<-EOF
    openssl req -batch -days #{node['openvpn']['key']['expire']} \
      -nodes -new -newkey rsa:#{key_size} -keyout #{key_dir}/server.key \
      -out #{key_dir}/server.csr -extensions server \
      -config #{key_dir}/openssl.cnf
  EOF
  not_if { File.exist?('#{key_dir}/server.crt') }
end

where code contains the OpenSSL command to be run. The not_if property tells Chef Infra Client not to run the command if the file already exists.

Install a file from a remote location using bash

The following is an example of how to install the foo123 module for Nginx. This module adds shell-style functionality to an Nginx configuration file and does the following:

  • Declares three variables
  • Gets the Nginx file from a remote location
  • Installs the file using Bash to the path specified by the src_filepath variable
# the following code sample is similar to the ``upload_progress_module``
# recipe in the ``nginx`` cookbook:
# https://github.com/chef-cookbooks/nginx

src_filename = "foo123-nginx-module-v#{
  node['nginx']['foo123']['version']
}.tar.gz"
src_filepath = "#{Chef::Config['file_cache_path']}/#{src_filename}"
extract_path = "#{
  Chef::Config['file_cache_path']
  }/nginx_foo123_module/#{
  node['nginx']['foo123']['checksum']
}"

remote_file 'src_filepath' do
  source node['nginx']['foo123']['url']
  checksum node['nginx']['foo123']['checksum']
  owner 'root'
  group 'root'
  mode '0755'
end

bash 'extract_module' do
  cwd ::File.dirname(src_filepath)
  code <<-EOH
    mkdir -p #{extract_path}
    tar xzf #{src_filename} -C #{extract_path}
    mv #{extract_path}/*/* #{extract_path}/
  EOH
  not_if { ::File.exist?(extract_path) }
end

Install an application from git using bash

The following example shows how Bash can be used to install a plug-in for rbenv named ruby-build, which is located in git version source control. First, the application is synchronized, and then Bash changes its working directory to the location in which ruby-build is located, and then runs a command.

git "#{Chef::Config[:file_cache_path]}/ruby-build" do
  repository 'git://github.com/sstephenson/ruby-build.git'
  revision 'master'
  action :sync
end

bash 'install_ruby_build' do
  cwd "#{Chef::Config[:file_cache_path]}/ruby-build"
  user 'rbenv'
  group 'rbenv'
  code <<-EOH
    ./install.sh
  EOH
  environment 'PREFIX' => '/usr/local'
end

To read more about ruby-build, see here: https://github.com/sstephenson/ruby-build.

Store certain settings

The following recipe shows how an attributes file can be used to store certain settings. An attributes file is located in the attributes/ directory in the same cookbook as the recipe which calls the attributes file. In this example, the attributes file specifies certain settings for Python that are then used across all nodes against which this recipe will run.

Python packages have versions, installation directories, URLs, and checksum files. An attributes file that exists to support this type of recipe would include settings like the following:

default['python']['version'] = '2.7.1'

if python['install_method'] == 'package'
  default['python']['prefix_dir'] = '/usr'
else
  default['python']['prefix_dir'] = '/usr/local'
end

default['python']['url'] = 'http://www.python.org/ftp/python'
default['python']['checksum'] = '80e387...85fd61'

and then the methods in the recipe may refer to these values. A recipe that is used to install Python will need to do the following:

  • Identify each package to be installed (implied in this example, not shown)
  • Define variables for the package version and the install_path
  • Get the package from a remote location, but only if the package does not already exist on the target system
  • Use the bash resource to install the package on the node, but only when the package is not already installed
#  the following code sample comes from the ``oc-nginx`` cookbook on |github|: https://github.com/cookbooks/oc-nginx

version = node['python']['version']
install_path = "#{node['python']['prefix_dir']}/lib/python#{version.split(/(^\d+\.\d+)/)[1]}"

remote_file "#{Chef::Config[:file_cache_path]}/Python-#{version}.tar.bz2" do
  source "#{node['python']['url']}/#{version}/Python-#{version}.tar.bz2"
  checksum node['python']['checksum']
  mode '0755'
  not_if { ::File.exist?(install_path) }
end

bash 'build-and-install-python' do
  cwd Chef::Config[:file_cache_path]
  code <<-EOF
    tar -jxvf Python-#{version}.tar.bz2
    (cd Python-#{version} && ./configure #{configure_options})
    (cd Python-#{version} && make && make install)
  EOF
  not_if { ::File.exist?(install_path) }
end

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
script 'mkdir test_dir' do
 interpreter "bash"
 code  "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username"
 password "password"
end

# Passing username and domain
script 'mkdir test_dir' do
 interpreter "bash"
 code  "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 domain "domain-name"
 user "username"
 password "password"
end

# Passing username = 'domain-name\\username'. No domain is passed
script 'mkdir test_dir' do
 interpreter "bash"
 code  "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "domain-name\\username"
 password "password"
end

# Passing username = 'username@domain-name'. No domain is passed
script 'mkdir test_dir' do
 interpreter "bash"
 code  "mkdir test_dir"
 cwd Chef::Config[:file_cache_path]
 user "username@domain-name"
 password "password"
end

service resource

service resource page

Use the service resource to manage a service.

Syntax


The full syntax for all of the properties that are available to the service resource is:

service 'name' do
  init_command         String
  options              Array, String
  parameters           Hash
  pattern              String
  priority             Integer, String, Hash
  reload_command       String, false
  restart_command      String, false
  run_levels           Array
  service_name         String # default value: 'name' unless specified
  start_command        String, false
  status_command       String, false
  stop_command         String, false
  supports             Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil}
  timeout              Integer # default value: 900
  user                 String
  action               Symbol # defaults to :nothing if not specified
end

where:

  • service is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • init_command, options, parameters, pattern, priority, reload_command, restart_command, run_levels, service_name, start_command, status_command, stop_command, supports, timeout, and user are the properties available to this resource.

Actions


The service resource has the following actions:

:disable
Disable a service. This action is equivalent to a Disabled startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot.
:enable
Enable a service at boot. This action is equivalent to an Automatic startup type on the Microsoft Windows platform. This action is not supported when using System Resource Controller (SRC) on the AIX platform because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot.
:nothing
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.
:reload
Reload the configuration for this service.
:restart
Restart a service.
:start
Start a service, and keep it running until stopped or disabled.
:stop
Stop a service.

Properties


The service resource has the following properties:

init_command
Ruby Type: String

The path to the init script that is associated with the service. Use init_command to prevent the need to specify overrides for the start_command, stop_command, and restart_command properties. When this property is not specified, Chef Infra Client will use the default init command for the service provider being used.

options
Ruby Type: Array, String

Solaris platform only. Options to pass to the service command. See the svcadm manual for details of possible options.

parameters
Ruby Type: Hash

Upstart only: A hash of parameters to pass to the service command for use in the service definition.

pattern
Ruby Type: String | Default Value: The value provided to 'service_name' or the resource block's name

The pattern to look for in the process table.

priority
Ruby Type: Integer, String, Hash

Debian platform only. The relative priority of the program for start and shutdown ordering. May be an integer or a Hash. An integer is used to define the start run levels; stop run levels are then 100-integer. A Hash is used to define values for specific run levels. For example, { 2 => [:start, 20], 3 => [:stop, 55] } will set a priority of twenty for run level two and a priority of fifty-five for run level three.

reload_command
Ruby Type: String, false

The command used to tell a service to reload its configuration.

restart_command
Ruby Type: String, false

The command used to restart a service.

run_levels
Ruby Type: Array

RHEL platforms only: Specific run_levels the service will run under.

service_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the service name if it differs from the resource block’s name.

start_command
Ruby Type: String, false

The command used to start a service.

status_command
Ruby Type: String, false

The command used to check the run status for a service.

stop_command
Ruby Type: String, false

The command used to stop a service.

supports
Ruby Type: Hash | Default Value: {"restart" => nil, "reload" => nil, "status" => nil}

A list of properties that controls how Chef Infra Client is to attempt to manage a service: :restart, :reload, :status. For :restart, the init script or other service provider can use a restart command; if :restart is not specified, Chef Infra Client attempts to stop and then start a service. For :reload, the init script or other service provider can use a reload command. For :status, the init script or other service provider can use a status command to determine if the service is running; if :status is not specified, Chef Infra Client attempts to match the service_name against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: { restart: false, reload: false, status: false } for all platforms (except for the Red Hat platform family, which defaults to { restart: false, reload: false, status: true }.)

timeout
Ruby Type: Integer | Default Value: 900

The amount of time (in seconds) to wait before timing out.

user
Ruby Type: String

systemd only: A username to run the service under.

New in Chef Client 12.21


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the service resource in recipes:

Start a service

service 'example_service' do
  action :start
end

Start a service, enable it

service 'example_service' do
  supports status: true, restart: true, reload: true
  action [ :enable, :start ]
end

Use a pattern

service 'samba' do
  pattern 'smbd'
  action [:enable, :start]
end

Use the :nothing common action

service 'memcached' do
  action :nothing
end

Use the retries common attribute

service 'apache' do
  action [ :enable, :start ]
  retries 3
end

Manage a service, depending on the node platform

service 'example_service' do
  if redhat?
    service_name 'redhat_name'
  else
    service_name 'other_name'
  end
  supports restart: true
  action [ :enable, :start ]
end

Reload a service using a template

To reload a service that is based on a template, use the template and service resources together in the same recipe, similar to the following:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
end

service 'apache' do
  action :enable
  subscribes :reload, 'template[/tmp/somefile]', :immediately
end

where the subscribes notification is used to reload the service whenever the template is modified.

Enable a service after a restart or reload

service 'apache' do
  supports restart: true, reload: true
  action :enable
end

Set an IP address using variables and a template

The following example shows how the template resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following:

default['nginx']['dir'] = '/etc/nginx'

The recipe then does the following to:

  • Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address
  • Use the service resource to restart and reload the Nginx service
  • Load a template named authorized_ip.erb from the /templates directory that is used to set the IP address values based on the variables specified in the recipe
node.default['nginx']['remote_ip_var'] = 'remote_addr'
node.default['nginx']['authorized_ips'] = ['127.0.0.1/32']

service 'nginx' do
  supports :status => true, :restart => true, :reload => true
end

template 'authorized_ip' do
  path "#{node['nginx']['dir']}/authorized_ip"
  source 'modules/authorized_ip.erb'
  owner 'root'
  group 'root'
  mode '0755'
  variables(
    :remote_ip_var => node['nginx']['remote_ip_var'],
    :authorized_ips => node['nginx']['authorized_ips']
  )

  notifies :reload, 'service[nginx]', :immediately
end

where the variables property tells the template to use the variables set at the beginning of the recipe and the source property is used to call a template file located in the cookbook’s /templates directory. The template file looks similar to:

geo $<%= @remote_ip_var %> $authorized_ip {
  default no;
  <% @authorized_ips.each do |ip| %>
  <%= "#{ip} yes;" %>
  <% end %>
}

Use a cron timer to manage a service

The following example shows how to install the crond application using two resources and a variable:

# the following code sample comes from the ``cron`` cookbook:
# https://github.com/chef-cookbooks/cron

cron_package = case node['platform']
  when 'redhat', 'centos', 'scientific', 'fedora', 'amazon'
    node['platform_version'].to_f >= 6.0 ? 'cronie' : 'vixie-cron'
  else
    'cron'
  end

package cron_package do
  action :install
end

service 'crond' do
  case node['platform']
  when 'redhat', 'centos', 'scientific', 'fedora', 'amazon'
    service_name 'crond'
  when 'debian', 'ubuntu', 'suse'
    service_name 'cron'
  end
  action [:start, :enable]
end

where

  • cron_package is a variable that is used to identify which platforms apply to which install packages
  • the package resource uses the cron_package variable to determine how to install the crond application on various nodes (with various platforms)
  • the service resource enables the crond application on nodes that have Red Hat, CentOS, Red Hat Enterprise Linux, Fedora, or Amazon Web Services (AWS), and the cron service on nodes that run Debian, Ubuntu, or openSUSE

Restart a service, and then notify a different service

The following example shows how start a service named example_service and immediately notify the Nginx service to restart.

service 'example_service' do
  action :start
  notifies :restart, 'service[nginx]', :immediately
end

Restart one service before restarting another

This example uses the :before notification to restart the php-fpm service before restarting nginx:

service 'nginx' do
  action :restart
  notifies :restart, 'service[php-fpm]', :before
end

With the :before notification, the action specified for the nginx resource will not run until action has been taken on the notified resource (php-fpm).

Stop a service, do stuff, and then restart it

The following example shows how to use the execute, service, and mount resources together to ensure that a node running on Amazon EC2 is running MySQL. This example does the following:

  • Checks to see if the Amazon EC2 node has MySQL
  • If the node has MySQL, stops MySQL
  • Installs MySQL
  • Mounts the node
  • Restarts MySQL
# the following code sample comes from the ``server_ec2``
# recipe in the following cookbook:
# https://github.com/chef-cookbooks/mysql

if (node.attribute?('ec2') && ! FileTest.directory?(node['mysql']['ec2_path']))

  service 'mysql' do
    action :stop
  end

  execute 'install-mysql' do
    command "mv #{node['mysql']['data_dir']} #{node['mysql']['ec2_path']}"
    not_if do FileTest.directory?(node['mysql']['ec2_path']) end
  end

  [node['mysql']['ec2_path'], node['mysql']['data_dir']].each do |dir|
    directory dir do
      owner 'mysql'
      group 'mysql'
    end
  end

  mount node['mysql']['data_dir'] do
    device node['mysql']['ec2_path']
    fstype 'none'
    options 'bind,rw'
    action [:mount, :enable]
  end

  service 'mysql' do
    action :start
  end

end

where

  • the two service resources are used to stop, and then restart the MySQL service
  • the execute resource is used to install MySQL
  • the mount resource is used to mount the node and enable MySQL

Control a service using the execute resource

Warning

This is an example of something that should NOT be done. Use the service resource to control a service, not the execute resource.

Do something like this:

service 'tomcat' do
  action :start
end

and NOT something like this:

execute 'start-tomcat' do
  command '/etc/init.d/tomcat6 start'
  action :run
end

There is no reason to use the execute resource to control a service because the service resource exposes the start_command property directly, which gives a recipe full control over the command issued in a much cleaner, more direct manner.

Enable a service on AIX using the mkitab command

The service resource does not support using the :enable and :disable actions with resources that are managed using System Resource Controller (SRC). This is because System Resource Controller (SRC) does not have a standard mechanism for enabling and disabling services on system boot.

One approach for enabling or disabling services that are managed by System Resource Controller (SRC) is to use the execute resource to invoke mkitab, and then use that command to enable or disable the service.

The following example shows how to install a service:

execute "install #{node['chef_client']['svc_name']} in SRC" do
  command "mkssys -s #{node['chef_client']['svc_name']}
                  -p #{node['chef_client']['bin']}
                  -u root
                  -S
                  -n 15
                  -f 9
                  -o #{node['chef_client']['log_dir']}/client.log
                  -e #{node['chef_client']['log_dir']}/client.log -a '
                  -i #{node['chef_client']['interval']}
                  -s #{node['chef_client']['splay']}'"
  not_if "lssrc -s #{node['chef_client']['svc_name']}"
  action :run
end

and then enable it using the mkitab command:

execute "enable #{node['chef_client']['svc_name']}" do
  command "mkitab '#{node['chef_client']['svc_name']}:2:once:/usr/bin/startsrc
                  -s #{node['chef_client']['svc_name']} > /dev/console 2>&1'"
  not_if "lsitab #{node['chef_client']['svc_name']}"
end

smartos_package resource

smartos_package resource page

Use the smartos_package resource to manage packages for the SmartOS platform.

Syntax


The full syntax for all of the properties that are available to the smartos_package resource is:

smartos_package 'name' do
  options           String, Array
  package_name      String
  source            String
  timeout           String, Integer
  version           String
  action            Symbol # defaults to :install if not specified
end

where:

  • smartos_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps 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 smartos_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
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 package.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The smartos_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

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

snap_package resource

snap_package resource page

Use the snap_package resource to manage snap packages on Debian and Ubuntu platforms.

New in Chef Infra Client 15.0.

Syntax


The full syntax for all of the properties that are available to the snap_package resource is:

snap_package 'name' do
  channel           String # default value: "stable"
  options           String, Array
  package_name      String, Array
  source            String
  timeout           String, Integer
  version           String, Array
  action            Symbol # defaults to :install if not specified
end

where:

  • snap_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.
  • channel, options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The snap_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:lock
Locks the apt package to a specific version.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:reconfig
Reconfigure a package. This action requires a response file.
:remove
Remove a package.
:unlock
Unlocks the apt package so that it can be upgraded to a newer version.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The snap_package resource has the following properties:

channel
Ruby Type: String | Default Value: stable
Allowed Values: "beta", "candidate", "edge", "stable"

The default channel. For example: stable.

options
Ruby Type: String, Array

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

solaris_package resource

solaris_package resource page

Use the solaris_package resource to manage packages on the Solaris platform.

Syntax


The full syntax for all of the properties that are available to the solaris_package resource is:

solaris_package 'name' do
  options           String, Array
  package_name      String
  source            String
  timeout           String, Integer
  version           String
  action            Symbol # defaults to :install if not specified
end

where:

  • solaris_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps 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 solaris_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
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 package.

Properties


The solaris_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

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the solaris_package resource in recipes:

Install a package

solaris_package 'name of package' do
  source '/packages_directory'
  action :install
end

ssh_known_hosts_entry resource

ssh_known_hosts_entry resource page

Use the ssh_known_hosts_entry resource to add an entry for the specified host in /etc/ssh/ssh_known_hosts or a user’s known hosts file if specified.

New in Chef Infra Client 14.3.

Syntax


The full syntax for all of the properties that are available to the ssh_known_hosts_entry resource is:

ssh_known_hosts_entry 'name' do
  file_location      String # default value: "/etc/ssh/ssh_known_hosts"
  group              String, Integer
  hash_entries       true, false # default value: false
  host               String # default value: 'name' unless specified
  key                String
  key_type           String # default value: "rsa"
  mode               String # default value: "0644"
  owner              String, Integer # default value: "root"
  port               Integer # default value: 22
  timeout            Integer # default value: 30
  action             Symbol # defaults to :create if not specified
end

where:

  • ssh_known_hosts_entry is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • file_location, group, hash_entries, host, key, key_type, mode, owner, port, and timeout are the properties available to this resource.

Actions


The ssh_known_hosts_entry resource has the following actions:

:create
Default. Create an entry in the ssh_known_hosts file.
:flush
Immediately flush the entries to the config file. Without this the actual writing of the file is delayed in the Chef run so all entries can be accumulated before writing the file out.
:nothing
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 ssh_known_hosts_entry resource has the following properties:

file_location
Ruby Type: String | Default Value: /etc/ssh/ssh_known_hosts

The location of the ssh known hosts file. Change this to set a known host file for a particular user.

group
Ruby Type: String, Integer

The file group for the ssh_known_hosts file.

hash_entries
Ruby Type: true, false | Default Value: false

Hash the hostname and addresses in the ssh_known_hosts file for privacy.

host
Ruby Type: String | Default Value: The resource block's name

The host to add to the known hosts file.

key
Ruby Type: String

An optional key for the host. If not provided this will be automatically determined.

key_type
Ruby Type: String | Default Value: rsa

The type of key to store.

mode
Ruby Type: String | Default Value: "0644"

The file mode for the ssh_known_hosts file.

owner
Ruby Type: String, Integer | Default Value: root

The file owner for the ssh_known_hosts file.

port
Ruby Type: Integer | Default Value: 22

The server port that the ssh-keyscan command will use to gather the public key.

timeout
Ruby Type: Integer | Default Value: 30

The timeout in seconds for ssh-keyscan.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the ssh_known_hosts_entry resource in recipes:

Add a single entry for github.com with the key auto detected

ssh_known_hosts_entry 'github.com'

Add a single entry with your own provided key

ssh_known_hosts_entry 'github.com' do
  key 'node.example.com ssh-rsa ...'
end

subversion resource

subversion resource page

Use the subversion resource to manage source control resources that exist in a Subversion repository.

Warning

The subversion resource has known bugs and may not work as expected. For more information see Chef GitHub issues, particularly #4050 and #4257.

Syntax


The full syntax for all of the properties that are available to the subversion resource is:

subversion 'name' do
  destination        String # default value: 'name' unless specified
  environment        Hash
  group              String, Integer
  repository         String
  revision           String # default value: "HEAD"
  svn_arguments      String, false # default value: "--no-auth-cache"
  svn_binary         String
  svn_info_args      String, false # default value: "--no-auth-cache"
  svn_password       String
  svn_username       String
  timeout            Integer
  user               String, Integer
  action             Symbol # defaults to :sync if not specified
end

where:

  • subversion is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • destination, environment, group, repository, revision, svn_arguments, svn_binary, svn_info_args, svn_password, svn_username, timeout, and user are the properties available to this resource.

Actions


The subversion resource has the following actions:

:checkout
Clone or check out the source. When a checkout is available, this provider does nothing.
:export
Export the source, excluding or removing any version control artifacts.
:force_export
Export the source, excluding or removing any version control artifacts and force an export of the source that is overwriting the existing copy (if it exists).
:nothing
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.
:sync
Default. Update the source to the specified version, or get a new clone or checkout. This action causes a hard reset of the index and working tree, discarding any uncommitted changes.

Properties


The subversion resource has the following properties:

destination
Ruby Type: String | Default Value: The resource block's name

The location path to which the source is to be cloned, checked out, or exported. Default value: the name of the resource block.

environment
Ruby Type: Hash

A Hash of environment variables in the form of ({‘ENV_VARIABLE’ => ‘VALUE’}).

group
Ruby Type: String, Integer

The system group that will own the checked-out code.

repository
Ruby Type: String

The URI of the code repository.

revision
Ruby Type: String | Default Value: HEAD

A branch, tag, or commit to be synchronized with git. This can be symbolic, like HEAD or it can be a source control management-specific revision identifier.

svn_arguments
Ruby Type: String, false | Default Value: --no-auth-cache

The extra arguments that are passed to the Subversion command.

svn_binary
Ruby Type: String

The location of the svn binary.

svn_info_args
Ruby Type: String, false | Default Value: --no-auth-cache

Use when the svn info command is used by Chef Infra Client and arguments need to be passed. The svn_arguments command does not work when the svn info command is used.

svn_password
Ruby Type: String

The password for a user that has access to the Subversion repository.

svn_username
Ruby Type: String

The user name for a user that has access to the Subversion repository.

timeout
Ruby Type: Integer

The amount of time (in seconds) to wait for a command to execute before timing out. When this property is specified using the deploy resource, the value of the timeout property is passed from the deploy resource to the subversion resource.

user
Ruby Type: String, Integer

The system user that will own the checked-out code.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the subversion resource in recipes:

Get the latest version of an application

subversion 'CouchDB Edge' do
  repository 'http://svn.apache.org/repos/asf/couchdb/trunk'
  revision 'HEAD'
  destination '/opt/mysources/couch'
  action :sync
end

sudo resource

sudo resource page

Use the sudo resource to add or remove individual sudo entries using sudoers.d files. Sudo version 1.7.2 or newer is required to use the sudo resource, as it relies on the #includedir directive introduced in version 1.7.2. This resource does not enforce installation of the required sudo version. Chef-supported releases of Ubuntu, SuSE, Debian, and RHEL (6+) all support this feature.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the sudo resource is:

sudo 'name' do
  command_aliases        Array
  commands               Array # default value: ["ALL"]
  config_prefix          String # default value: "Prefix values based on the node's platform"
  defaults               Array
  env_keep_add           Array
  env_keep_subtract      Array
  filename               String # default value: 'name' unless specified
  groups                 String, Array
  host                   String # default value: "ALL"
  noexec                 true, false # default value: false
  nopasswd               true, false # default value: false
  runas                  String # default value: "ALL"
  setenv                 true, false # default value: false
  template               String
  users                  String, Array
  variables              Hash
  visudo_binary          String # default value: "/usr/sbin/visudo"
  action                 Symbol # defaults to :create if not specified
end

where:

  • sudo is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • command_aliases, commands, config_prefix, defaults, env_keep_add, env_keep_subtract, filename, groups, host, noexec, nopasswd, runas, setenv, template, users, variables, and visudo_binary are the properties available to this resource.

Actions


The sudo resource has the following actions:

:create
Default. Create a single sudoers configuration file in the sudoers.d directory.
:delete
Removed a sudoers configuration file from the sudoers.d directory.
:nothing
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 sudo resource has the following properties:

command_aliases
Ruby Type: Array

Command aliases that can be used as allowed commands later in the configuration.

commands
Ruby Type: Array | Default Value: ["ALL"]

An array of full paths to commands this sudoer can execute.

config_prefix
Ruby Type: String | Default Value: Prefix values based on the node's platform

The directory that contains the sudoers configuration file.

defaults
Ruby Type: Array

An array of defaults for the user/group.

env_keep_add
Ruby Type: Array

An array of strings to add to env_keep.

env_keep_subtract
Ruby Type: Array

An array of strings to remove from env_keep.

filename
Ruby Type: String | Default Value: The resource block's name

The name of the sudoers.d file if it differs from the name of the resource block

groups
Ruby Type: String, Array

Group(s) to provide sudo privileges to. This property accepts either an array or a comma separated list. Leading % on group names is optional.

host
Ruby Type: String | Default Value: ALL

The host to set in the sudo configuration.

noexec
Ruby Type: true, false | Default Value: false

Prevent commands from shelling out.

nopasswd
Ruby Type: true, false | Default Value: false

Allow sudo to be run without specifying a password.

runas
Ruby Type: String | Default Value: ALL

User that the command(s) can be run as.

setenv
Ruby Type: true, false | Default Value: false

Determines whether or not to permit preservation of the environment with sudo -E.

template
Ruby Type: String

The name of the erb template in your cookbook, if you wish to supply your own template.

users
Ruby Type: String, Array

User(s) to provide sudo privileges to. This property accepts either an array or a comma separated list.

variables
Ruby Type: Hash

The variables to pass to the custom template. This property is ignored if not using a custom template.

visudo_binary
Ruby Type: String | Default Value: /usr/sbin/visudo

The path to visudo for configuration verification.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the sudo resource in recipes:

Grant a user sudo privileges for any command

sudo 'admin' do
  user 'admin'
end

Grant a user and groups sudo privileges for any command

sudo 'admins' do
  users 'bob'
  groups 'sysadmins, superusers'
end

Grant passwordless sudo privileges for specific commands

sudo 'passwordless-access' do
  commands ['/bin/systemctl restart httpd', '/bin/systemctl restart mysql']
  nopasswd true
end

swap_file resource

swap_file resource page

Use the swap_file resource to create or delete swap files on Linux systems, and optionally to manage the swappiness configuration for a host.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the swap_file resource is:

swap_file 'name' do
  path            String # default value: 'name' unless specified
  persist         true, false # default value: false
  size            Integer
  swappiness      Integer
  timeout         Integer # default value: 600
  action          Symbol # defaults to :create if not specified
end

where:

  • swap_file is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • path, persist, size, swappiness, and timeout are the properties available to this resource.

Actions


The swap_file resource has the following actions:

:create
Default. Create a swap file.
: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 swap file and disable swap.

Properties


The swap_file resource has the following properties:

path
Ruby Type: String | Default Value: The resource block's name

The path where the swap file will be created on the system if it differs from the resource block’s name.

persist
Ruby Type: true, false | Default Value: false

Persist the swapon.

size
Ruby Type: Integer

The size (in MBs) of the swap file.

swappiness
Ruby Type: Integer

The swappiness value to set on the system.

timeout
Ruby Type: Integer | Default Value: 600

Timeout for dd / fallocate commands.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the swap_file resource in recipes:

Create a swap file

swap_file '/dev/sda1' do
  size 1024
end

Remove a swap file

swap_file '/dev/sda1' do
  action :remove
end

sysctl resource

sysctl resource page

Use the sysctl resource to set or remove kernel parameters using the sysctl command line tool and configuration files in the system’s sysctl.d directory. Configuration files managed by this resource are named 99-chef-KEYNAME.conf.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the sysctl resource is:

sysctl 'name' do
  comment           Array, String # default value: []
  conf_dir          String # default value: "/etc/sysctl.d"
  ignore_error      true, false # default value: false
  key               String # default value: 'name' unless specified
  value             Array, String, Integer, Float
  action            Symbol # defaults to :apply if not specified
end

where:

  • sysctl is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • comment, conf_dir, ignore_error, key, and value are the properties available to this resource.

Actions


The sysctl resource has the following actions:

:apply
Default. Set the kernel parameter and update the sysctl settings.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:remove
Remove the kernel parameter and update the sysctl settings.

Properties


The sysctl resource has the following properties:

comment
Ruby Type: Array, String | Default Value: []

Comments, placed above the resource setting in the generated file. For multi-line comments, use an array of strings, one per line.

New in Chef Infra Client 15.8

conf_dir
Ruby Type: String | Default Value: /etc/sysctl.d

The configuration directory to write the config to.

ignore_error
Ruby Type: true, false | Default Value: false

Ignore any errors when setting the value on the command line.

key
Ruby Type: String | Default Value: The resource block's name

The kernel parameter key in dotted format if it differs from the resource block’s name.

value
Ruby Type: Array, String, Integer, Float | REQUIRED

The value to set.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the sysctl resource in recipes:

Set vm.swappiness:

sysctl 'vm.swappiness' do
  value 19
end

Remove kernel.msgmax:

Note: This only removes the sysctl.d config for kernel.msgmax. The value will be set back to the kernel default value.

sysctl 'kernel.msgmax' do
  action :remove
end

Adding Comments to sysctl configuration files:

sysctl 'vm.swappiness' do
  value 19
  comment "define how aggressively the kernel will swap memory pages."
end

This produces /etc/sysctl.d/99-chef-vm.swappiness.conf as follows:

# define how aggressively the kernel will swap memory pages.
vm.swappiness = 1

Converting sysctl settings from shell scripts:

Example of existing settings:

fs.aio-max-nr = 1048576 net.ipv4.ip_local_port_range = 9000 65500 kernel.sem = 250 32000 100 128

Converted to sysctl resources:

sysctl 'fs.aio-max-nr' do
  value '1048576'
end

sysctl 'net.ipv4.ip_local_port_range' do
  value '9000 65500'
end

sysctl 'kernel.sem' do
  value '250 32000 100 128'
end

systemd_unit resource

systemd_unit resource page

Use the systemd_unit resource to create, manage, and run systemd units.

New in Chef Infra Client 12.11.

Syntax


The full syntax for all of the properties that are available to the systemd_unit resource is:

systemd_unit 'name' do
  content              String, Hash
  triggers_reload      true, false # default value: true
  unit_name            String # default value: 'name' unless specified
  user                 String
  verify               true, false # default value: true
  action               Symbol # defaults to :nothing if not specified
end

where:

  • systemd_unit 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.
  • content, triggers_reload, unit_name, user, and verify are the properties available to this resource.

Actions


The systemd_unit resource has the following actions:

:create
Create a unit file, if it does not already exist.
:delete
Delete a unit file, if it exists.
:disable
Ensure the unit will not be started after the next system boot.
:enable
Ensure the unit will be started after the next system boot.
:mask
Ensure the unit will not start, even to satisfy dependencies.
:nothing
Default. Do nothing with the unit.
:preset
Restore the preset “enable/disable” configuration for a unit. New in Chef Client 14.0.
:reenable
Reenable a unit file. New in Chef Client 14.0.
:reload
Reload the configuration file for a unit.
:reload_or_restart
For units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will restart the service so the new configuration is applied.
:reload_or_try_restart
For units that are services, this action reloads the configuration of the service without restarting, if possible; otherwise, it will try to restart the service so the new configuration is applied.
:restart
Restart a unit.
:revert
Revet to a vendor’s version of a unit file. New in Chef Client 14.0.
:start
Start a unit based in its systemd unit file.
:stop
Stop a running unit.
:try_restart
Try to restart a unit if the unit is running.
:unmask
Stop the unit from being masked and cause it to start as specified.

Properties


The systemd_unit resource has the following properties:

content
Ruby Type: String, Hash

A string or hash that contains a systemd unit file definition that describes the properties of systemd-managed entities, such as services, sockets, devices, and so on. In Chef Infra Client 14.4 or later, repeatable options can be implemented with an array.

triggers_reload
Ruby Type: true, false | Default Value: true

Specifies whether to trigger a daemon reload when creating or deleting a unit.

unit_name
Ruby Type: String | Default Value: The resource block's name

The name of the unit file if it differs from the resource block’s name.

New in Chef Client 13.7

user
Ruby Type: String

The user account that the systemd unit process is run under. The path to the unit for that user would be something like ‘/etc/systemd/user/sshd.service’. If no user account is specified, the systemd unit will run under a ‘system’ account, with the path to the unit being something like ‘/etc/systemd/system/sshd.service’.

verify
Ruby Type: true, false | Default Value: true

Specifies if the unit will be verified before installation. Systemd can be overly strict when verifying units, so in certain cases it is preferable not to verify the unit.

Unit file verification

The unit file is verified via a systemd-analyze verify call before being written to disk.

Be aware that the referenced commands and files need to already exist before verification.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the systemd_unit resource in recipes:

Create etcd systemd service unit file from a Hash

systemd_unit 'etcd.service' do
  content({Unit: {
            Description: 'Etcd',
            Documentation: ['https://coreos.com/etcd', 'man:etcd(1)'],
            After: 'network.target',
          },
          Service: {
            Type: 'notify',
            ExecStart: '/usr/local/etcd',
            Restart: 'always',
          },
          Install: {
            WantedBy: 'multi-user.target',
          }})
  action [:create, :enable]
end

Create etcd systemd service unit file from a String

systemd_unit 'sysstat-collect.timer' do
  content <<-EOU.gsub(/^\s+/, '')
  [Unit]
  Description=Run system activity accounting tool every 10 minutes

  [Timer]
  OnCalendar=*:00/10

  [Install]
  WantedBy=sysstat.service
  EOU

  action [:create, :enable]
end

template resource

template resource page

A cookbook template is an Embedded Ruby (ERB) template that is used to dynamically generate static text files. Templates may contain Ruby expressions and statements, and are a great way to manage configuration files. Use the template resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template file in a cookbook’s /templates directory.

Note

The Chef Infra Client uses Erubis for templates, which is a fast, secure, and extensible implementation of embedded Ruby. Erubis should be familiar to members of the Ruby on Rails, Merb, or Puppet communities. For more information about Erubis, see: http://www.kuwata-lab.com/erubis/.

Use the template resource to manage the contents of a file using an Embedded Ruby (ERB) template by transferring files from a sub-directory of COOKBOOK_NAME/templates/ to a specified path located on a host that is running Chef Infra Client. This resource includes actions and properties from the file resource. Template files managed by the template resource follow the same file specificity rules as the remote_file and file resources.

Syntax


A template resource block typically declares the location in which a file is to be created, the source template that will be used to create the file, and the permissions needed on that file. For example:

template '/etc/motd' do
  source 'motd.erb'
  owner 'root'
  group 'root'
  mode '0755'
end

where:

  • '/etc/motd' specifies the location in which the file is created
  • 'motd.erb' specifies the name of a template that exists in in the /templates folder of a cookbook
  • owner, group, and mode define the permissions

The full syntax for all of the properties that are available to the template resource is:

template 'name' do
  atomic_update              true, false
  backup                     false, Integer
  cookbook                   String
  force_unlink               true, false
  group                      String, Integer
  helper(:method)            Method { String } # see Helpers below
  helpers(module)            Module # see Helpers below
  inherits                   true, false
  local                      true, false
  manage_symlink_source      true, false
  mode                       String, Integer
  owner                      String, Integer
  path                       String # defaults to 'name' if not specified
  rights                     Hash
  sensitive                  true, false
  source                     String, Array
  variables                  Hash
  verify                     String, Block
  action                     Symbol # defaults to :create if not specified
end

where:

  • template is the resource
  • name is the name of the resource block, typically the path to the location in which a file is created and also the name of the file to be managed. For example: /var/www/html/index.html, where /var/www/html/ is the fully qualified path to the location and index.html is the name of the file
  • source is the template file that will be used to create the file on the node, for example: index.html.erb; the template file is located in the /templates directory of a cookbook
  • action identifies the steps Chef Infra Client will take to bring the node into the desired state
  • atomic_update, backup, cookbook, force_unlink, group, helper, helpers, inherits, local, manage_symlink_source, mode, owner, path, rights, sensitive, source, variables, and verify are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The template resource has the following actions:

:create
Default. Create a file. If a file already exists (but does not match), update that file to match.
:create_if_missing
Create a file only if the file does not exist. When the file exists, nothing happens.
:delete
Delete a file.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:touch
Touch a file. This updates the access (atime) and file modification (mtime) times for a file. (This action may be used with this resource, but is typically only used with the file resource.)

Properties


The template resource has the following properties:

atomic_update
Ruby Type: true, false

Perform atomic file updates on a per-resource basis. Set to true for atomic file updates. Set to false for non-atomic file updates. This setting overrides file_atomic_update, which is a global setting found in the client.rb file.

backup
Ruby Type: Integer, false | Default Value: 5

The number of backups to be kept in /var/chef/backup (for UNIX- and Linux-based platforms) or C:/chef/backup (for the Microsoft Windows platform). Set to false to prevent backups from being kept.

cookbook
Ruby Type: String

The cookbook in which a file is located (if it is not located in the current cookbook). The default value is the current cookbook.

force_unlink
Ruby Type: true, false | Default Value: false

How Chef Infra Client handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to true for Chef Infra Client delete the non-file target and replace it with the specified file. Set to false for Chef Infra Client to raise an error.

group
Ruby Type: Integer, String

A string or ID that identifies the group owner by group name or SID, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available).

helper
Ruby Type: Method | Default Value: {}

Define a helper method inline. For example: helper(:hello_world) { "hello world" } or helper(:app) { node["app"] } or helper(:app_conf) { |setting| node["app"][setting] }.

helpers
Ruby Type: Module | Default Value: []

Define a helper module inline or in a library. For example, an inline module: helpers do, which is then followed by a block of Ruby code. And for a library module: helpers(MyHelperModule).

inherits
Ruby Type: true, false | Default Value: true

Microsoft Windows only. Whether a file inherits rights from its parent directory.

local
Ruby Type: true, false | Default Value: false

Load a template from a local path. By default, Chef Infra Client loads templates from a cookbook’s /templates directory. When this property is set to true, use the source property to specify the path to a template on the local node.

manage_symlink_source
Ruby Type: true, false | Default Value: true

(with warning)

Change the behavior of the file resource if it is pointed at a symlink. When this value is set to true, Chef Infra Client will manage the symlink’s permissions or will replace the symlink with a normal file if the resource has content. When this value is set to false, Chef will follow the symlink and will manage the permissions and content of the symlink’s target file.

The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning.

mode
Ruby Type: Integer, String

A quoted 3-5 character string that defines the octal mode. For example: '755', '0755', or 00755. If mode is not specified and if the file already exists, the existing mode on the file is used. If mode is not specified, the file does not exist, and the :create action is specified, Chef Infra Client assumes a mask value of '0777' and then applies the umask for the system on which the file is to be created to the mask value. For example, if the umask on a system is '022', Chef Infra Client uses the default value of '0755'.

The behavior is different depending on the platform.

UNIX- and Linux-based systems: A quoted 3-5 character string that defines the octal mode that is passed to chmod. For example: '755', '0755', or 00755. If the value is specified as a quoted string, it works exactly as if the chmod command was passed. If the value is specified as an integer, prepend a zero (0) to the value to ensure that it is interpreted as an octal number. For example, to assign read, write, and execute rights for all users, use '0777' or '777'; for the same rights, plus the sticky bit, use 01777 or '1777'.

Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative.

owner
Ruby Type: Integer, String

A string or ID that identifies the group owner by user name or SID, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary).

path
Ruby Type: String | Default Value: The resource block's name

The full path to the file, including the file name and its extension.

Microsoft Windows: A path that begins with a forward slash (/) will point to the root of the current working directory of Chef Infra Client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended.

rights
Ruby Type: Integer, String

Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options.

source
Ruby Type: String, Array

The location of a template file. By default, Chef Infra Client looks for a template file in the /templates directory of a cookbook. When the local property is set to true, use to specify the path to a template on the local node. This property may also be used to distribute specific files to specific platforms. See “File Specificity” below for more information. Default value: the name of the resource block. See “Syntax” section above for more information.

variables
Ruby Type: Hash

A Hash of variables that are passed into a Ruby template file.

The variables property of the template resource can be used to reference a partial template file by using a Hash. For example:

template '/file/name.txt' do
  variables partials: {
    'partial_name_1.txt.erb' => 'message',
    'partial_name_2.txt.erb' => 'message',
    'partial_name_3.txt.erb' => 'message',
  }
end

where each of the partial template files can then be combined using normal Ruby template patterns within a template file, such as:

<% @partials.each  do |partial, message| %>
  Here is <%= partial %>
  <%= render partial, :variables => {:message => message} %>
<% end %>

verify
Ruby Type: String, Block

A block or a string that returns true or false. A string, when true is executed as a system command.

A block is arbitrary Ruby defined within the resource block by using the verify property. When a block is true, Chef Infra Client will continue to update the file as appropriate.

For example, this should return true:

template '/tmp/baz' do
  verify { 1 == 1 }
end

This should return true:

template '/etc/nginx.conf' do
  verify 'nginx -t -c %{path}'
end

This should return true:

template '/tmp/bar' do
  verify { 1 == 1}
end

And this should return true:

template '/tmp/foo' do
  verify do |path|
    true
  end
end

Whereas, this should return false:

template '/tmp/turtle' do
  verify '/usr/bin/false'
end

If a string or a block return false, the Chef Infra Client run will stop and an error is returned.

Atomic File Updates

Atomic updates are used with file-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out.

Atomic updates are enabled by default. They can be managed globally using the file_atomic_update setting in the client.rb file. They can be managed on a per-resource basis using the atomic_update property that is available with the cookbook_file, file, remote_file, and template resources.

Note

On certain platforms, and after a file has been moved into place, Chef Infra Client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, Chef Infra Client will fix up the security contexts after a file has been moved into the correct location by running the restorecon command. On the Microsoft Windows platform, Chef Infra Client will create files so that ACL inheritance works as expected.

Windows File Security

To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes. Access Control Lists (ACLs)

The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; Chef Infra Client will apply them to the file or directory as required. The syntax for the rights property is as follows:

rights permission, principal, option_type => value

where

permission

Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control.

These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read.

(For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.)

principal

Use to specify a group or user. The principal can be specified by either name or SID. When using name, this is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the SDDL string constants. Chef Infra Client does not need to know if a principal is a user or a group.

option_type

A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types:

Option TypeDescription
:applies_to_childrenSpecify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories).
:applies_to_selfIndicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files.
:one_level_deepIndicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children.

For example:

resource 'x.txt' do
  rights :read, 'S-1-1-0'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
end

or:

rights :read, ['Administrators','Everyone']
rights :full_control, 'Users', :applies_to_children => true
rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true

Some other important things to know when using the rights attribute:

  • Only inherited rights remain. All existing explicit rights on the object are removed and replaced.
  • If rights are not specified, nothing will be changed. Chef Infra Client does not clear out the rights on a file or directory if rights are not specified.
  • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration.

Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example:

resource 'x.txt' do
  rights :read, 'Everyone'
  rights :write, 'domain\group'
  rights :full_control, 'group_name_or_user_name'
  rights :full_control, 'user_name', :applies_to_children => true
  deny_rights :read, ['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.

Using Templates

To use a template, two things must happen:

  1. A template resource must be added to a recipe
  2. An Embedded Ruby (ERB) template must be added to a cookbook

For example, the following template file and template resource settings can be used to manage a configuration file named /etc/sudoers. Within a cookbook that uses sudo, the following resource could be added to /recipes/default.rb:

template '/etc/sudoers' do
  source 'sudoers.erb'
  mode '0440'
  owner 'root'
  group 'root'
  variables(sudoers_groups: node['authorization']['sudo']['groups'],
            sudoers_users: node['authorization']['sudo']['users'])
end

And then create a template called sudoers.erb and save it to templates/default/sudoers.erb:

#
# /etc/sudoers
#
# Generated by Chef for <%= node['fqdn'] %>
#

Defaults        !lecture,tty_tickets,!fqdn

# User privilege specification
root          ALL=(ALL) ALL

<% @sudoers_users.each  do |user| -%>
<%= user %>   ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL
<% end -%>

# Members of the sysadmin group may gain root privileges
%sysadmin     ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL

<% @sudoers_groups.each do |group| -%>
# Members of the group '<%= group %>' may gain root privileges
<%= group %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL
<% end -%>

And then set the default attributes in attributes/default.rb:

default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin)
default['authorization']['sudo']['users'] = %w(jerry greg)

File Specificity

A cookbook is frequently designed to work across many platforms and is often required to distribute a specific template to a specific platform. A cookbook can be designed to support the distribution of templates across platforms, while ensuring that the correct template ends up on each system.

The pattern for template specificity depends on two things: the lookup path and the source. The first pattern that matches is used:

  1. /host-$fqdn/$source
  2. /$platform-$platform_version/$source
  3. /$platform/$source
  4. /default/$source
  5. /$source

Note

To specify a particular Windows version, use the operating system version number. For example, a template in templates/windows-6.3 will be deployed on systems installed with Windows 8.1.

Use an array with the source property to define an explicit lookup path. For example:

template '/test' do
  source ["#{node.chef_environment}.erb", 'default.erb']
end

The following example emulates the entire file specificity pattern by defining it as an explicit path:

template '/test' do
  source %W(
    host-#{node['fqdn']}/test.erb
    #{node['platform']}-#{node['platform_version']}/test.erb
    #{node['platform']}/test.erb
    default/test.erb
  )
end

A cookbook may have a /templates directory structure like this:

/templates/
  windows-10
  windows-6.3
  windows
  default

and a resource that looks something like the following:

template 'C:\path\to\file\text_file.txt' do
  source 'text_file.txt'
  mode '0755'
  owner 'root'
  group 'root'
end

This resource would be matched in the same order as the /templates directory structure. For a node named host-node-desktop that is running Windows 8.1, the second item would be the matching item and the location:

/templates
  windows-10/text_file.txt
  windows-6.3/text_file.txt
  windows/text_file.txt
  default/text_file.txt

Helpers

A helper is a method or a module that can be used to extend a template. There are three approaches:

  • An inline helper method
  • An inline helper module
  • A cookbook library module

Use the helper attribute in a recipe to define an inline helper method. Use the helpers attribute to define an inline helper module or a cookbook library module.

Inline Methods

A template helper method is always defined inline on a per-resource basis. A simple example:

template '/path' do
  helper(:hello_world) { 'hello world' }
end

Another way to define an inline helper method is to reference a node object so that repeated calls to one (or more) cookbook attributes can be done efficiently:

template '/path' do
  helper(:app) { node['app'] }
end

An inline helper method can also take arguments:

template '/path' do
  helper(:app_conf) { |setting| node['app'][setting] }
end

Once declared, a template can then use the helper methods to build a file. For example:

Say hello: <%= hello_world %>

or:

node['app']['listen_port'] is: <%= app['listen_port'] %>

or:

node['app']['log_location'] is: <%= app_conf('log_location') %>

Inline Modules

A template helper module can be defined inline on a per-resource basis. This approach can be useful when a template requires more complex information. For example:

template '/path' do
  helpers do

    def hello_world
      'hello world'
    end

    def app
      node['app']
    end

    def app_conf(setting)
      node['app']['setting']
    end

  end
end

where the hello_world, app, and app_conf(setting) methods comprise the module that extends a template.

Library Modules

A template helper module can be defined in a library. This is useful when extensions need to be reused across recipes or to make it easier to manage code that would otherwise be defined inline on a per-recipe basis.

template '/path/to/template.erb' do
  helpers(MyHelperModule)
end

Host Notation

The naming of folders within cookbook directories must literally match the host notation used for template specificity matching. For example, if a host is named foo.example.com, then the folder must be named host-foo.example.com.

Partial Templates

A template can be built in a way that allows it to contain references to one (or more) smaller template files. (These smaller template files are also referred to as partials.) A partial can be referenced from a template file in one of the following ways:

  • By using the render method in the template file
  • By using the template resource and the variables property.

render Method

Use the render method in a template to reference a partial template file:

<%= render 'partial_name.txt.erb', :option => {} %>

where partial_name is the name of the partial template file and :option is one (or more) of the following:

OptionDescription
:cookbookBy default, a partial template file is assumed to be located in the cookbook that contains the top-level template. Use this option to specify the path to a different cookbook
:localIndicates that the name of the partial template file should be interpreted as a path to a file in the local file system or looked up in a cookbook using the normal rules for template files. Set to true to interpret as a path to a file in the local file system and to false to use the normal rules for template files
:sourceBy default, a partial template file is identified by its file name. Use this option to specify a different name or a local path to use (instead of the name of the partial template file)
:variablesA hash of variable_name => value that will be made available to the partial template file. When this option is used, any variables that are defined in the top-level template that are required by the partial template file must have them defined explicitly using this option

For example:

<%= render 'simple.txt.erb', :variables => {:user => Etc.getlogin }, :local => true %>

Transfer Frequency

The Chef Infra Client caches a template when it is first requested. On each subsequent request for that template, the Chef Infra Client compares that request to the template located on the Chef Infra Server. If the templates are the same, no transfer occurs.

Variables

An Embedded Ruby (ERB) template allows Ruby code to be embedded inside a text file within specially formatted tags. Ruby code can be embedded using expressions and statements. An expression is delimited by <%= and %>. For example:

<%= "my name is #{$ruby}" %>

A statement is delimited by a modifier, such as if, elsif, and else. For example:

if false
# this won't happen
elsif nil
      # this won't either
    end

Using a Ruby expression is the most common approach for defining template variables because this is how all variables that are sent to a template are referenced. Whenever a template needs to use an each, if, or end, use a Ruby statement.

When a template is rendered, Ruby expressions and statements are evaluated by Chef Infra Client. The variables listed in the template resource’s variables parameter and in the node object are evaluated. Chef Infra Client then passes these variables to the template, where they will be accessible as instance variables within the template. The node object can be accessed just as if it were part of a recipe, using the same syntax.

For example, a simple template resource like this:

node['fqdn'] = 'latte'
template '/tmp/foo' do
  source 'foo.erb'
  variables(x_men: 'are keen')
end

And a simple Embedded Ruby (ERB) template like this:

The node <%= node[:fqdn] %> thinks the x-men <%= @x_men %>

Would render something like:

The node latte thinks the x-men are keen

Even though this is a very simple example, the full capabilities of Ruby can be used to tackle even the most complex and demanding template requirements.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the template resource in recipes:

Configure a file from a template

template '/tmp/config.conf' do
  source 'config.conf.erb'
end

Configure a file from a local template

template '/tmp/config.conf' do
  local true
  source '/tmp/config.conf.erb'
end

Configure a file using a variable map

template '/tmp/config.conf' do
  source 'config.conf.erb'
  variables(
    :config_var => node['configs']['config_var']
  )
end

Use the not_if condition

The following example shows how to use the not_if condition to create a file based on a template and using the presence of an attribute value on the node to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  not_if { node['some_value'] }
end

The following example shows how to use the not_if condition to create a file based on a template and then Ruby code to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  not_if do
    File.exist?('/etc/passwd')
  end
end

The following example shows how to use the not_if condition to create a file based on a template and using a Ruby block (with curly braces) to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  not_if { File.exist?('/etc/passwd') }
end

The following example shows how to use the not_if condition to create a file based on a template and using a string to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  not_if 'test -f /etc/passwd'
end

Use the only_if condition

The following example shows how to use the only_if condition to create a file based on a template and using the presence of an attribute on the node to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  only_if { node['some_value'] }
end

The following example shows how to use the only_if condition to create a file based on a template, and then use Ruby to specify a condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  only_if { ! ::File.exist?('/etc/passwd') }
end

The following example shows how to use the only_if condition to create a file based on a template and using a string to specify the condition:

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  only_if 'test -f /etc/passwd'
end

Use a whitespace array (%w)

The following example shows how to use a Ruby whitespace array to define a list of configuration tools, and then use that list of tools within the template resource to ensure that all of these configuration tools are using the same RSA key:

%w{openssl.cnf pkitool vars Rakefile}.each do |f|
  template "/etc/openvpn/easy-rsa/#{f}" do
    source "#{f}.erb"
    owner 'root'
    group 'root'
    mode '0755'
  end
end

Use a relative path

template "#{ENV['HOME']}/chef-getting-started.txt" do
  source 'chef-getting-started.txt.erb'
  mode '0755'
end

Delay notifications

template '/etc/nagios3/configures-nagios.conf' do
  # other parameters
  notifies :run, 'execute[test-nagios-config]', :delayed
end

Notify immediately

By default, notifications are :delayed, that is they are queued up as they are triggered, and then executed at the very end of a Chef 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-solr]', :delayed
  notifies :restart, 'service[chef-solr-indexer]', :delayed
  notifies :restart, 'service[chef-server]', :delayed
end

Reload a service

template '/tmp/somefile' do
  mode '0755'
  source 'somefile.erb'
  notifies :reload, 'service[apache]', :immediately
end

Restart a service when a template is modified

template '/etc/www/configures-apache.conf' do
  notifies :restart, 'service[apache]', :immediately
end

Send notifications to multiple resources

To send notifications to multiple resources, just use multiple attributes. Multiple attributes will get sent to the notified resources in the order specified.

template '/etc/netatalk/netatalk.conf' do
  notifies :restart, 'service[afpd]', :immediately
  notifies :restart, 'service[cnid]', :immediately
end

service 'afpd'
service 'cnid'

Execute a command using a template

The following example shows how to set up IPv4 packet forwarding using the execute resource to run a command named forward_ipv4 that uses a template defined by the template resource:

execute 'forward_ipv4' do
  command 'echo > /proc/.../ipv4/ip_forward'
  action :nothing
end

template '/etc/file_name.conf' do
  source 'routing/file_name.conf.erb'
  notifies :run, 'execute[forward_ipv4]', :delayed
end

where the command property for the execute resource contains the command that is to be run and the source property for the template resource specifies which template to use. The notifies property for the template specifies that the execute[forward_ipv4] (which is defined by the execute resource) should be queued up and run at the end of a Chef Infra Client run.

Set an IP address using variables and a template

The following example shows how the template resource can be used in a recipe to combine settings stored in an attributes file, variables within a recipe, and a template to set the IP addresses that are used by the Nginx service. The attributes file contains the following:

default['nginx']['dir'] = '/etc/nginx'

The recipe then does the following to:

  • Declare two variables at the beginning of the recipe, one for the remote IP address and the other for the authorized IP address
  • Use the service resource to restart and reload the Nginx service
  • Load a template named authorized_ip.erb from the /templates directory that is used to set the IP address values based on the variables specified in the recipe
node.default['nginx']['remote_ip_var'] = 'remote_addr'
node.default['nginx']['authorized_ips'] = ['127.0.0.1/32']

service 'nginx' do
  supports :status => true, :restart => true, :reload => true
end

template 'authorized_ip' do
  path "#{node['nginx']['dir']}/authorized_ip"
  source 'modules/authorized_ip.erb'
  owner 'root'
  group 'root'
  mode '0755'
  variables(
    :remote_ip_var => node['nginx']['remote_ip_var'],
    :authorized_ips => node['nginx']['authorized_ips']
  )

  notifies :reload, 'service[nginx]', :immediately
end

where the variables property tells the template to use the variables set at the beginning of the recipe and the source property is used to call a template file located in the cookbook’s /templates directory. The template file looks similar to:

geo $<%= @remote_ip_var %> $authorized_ip {
  default no;
  <% @authorized_ips.each do |ip| %>
  <%= "#{ip} yes;" %>
  <% end %>
}

Add a rule to an IP table

The following example shows how to add a rule named test_rule to an IP table using the execute resource to run a command using a template that is defined by the template resource:

execute 'test_rule' do
  command 'command_to_run
    --option value
    ...
    --option value
    --source #{node[:name_of_node][:ipsec][:local][:subnet]}
    -j test_rule'
  action :nothing
end

template '/etc/file_name.local' do
  source 'routing/file_name.local.erb'
  notifies :run, 'execute[test_rule]', :delayed
end

where the command property for the execute resource contains the command that is to be run and the source property for the template resource specifies which template to use. The notifies property for the template specifies that the execute[test_rule] (which is defined by the execute resource) should be queued up and run at the end of a Chef Infra Client run.

Apply proxy settings consistently across a Chef organization

The following example shows how a template can be used to apply consistent proxy settings for all nodes of the same type:

template "#{node['matching_node']['dir']}/sites-available/site_proxy.conf" do
  source 'site_proxy.matching_node.conf.erb'
  owner 'root'
  group 'root'
  mode '0755'
  variables(
    :ssl_certificate =>    "#{node['matching_node']['dir']}/shared/certificates/site_proxy.crt",
    :ssl_key =>            "#{node['matching_node']['dir']}/shared/certificates/site_proxy.key",
    :listen_port =>        node['site']['matching_node_proxy']['listen_port'],
    :server_name =>        node['site']['matching_node_proxy']['server_name'],
    :fqdn =>               node['fqdn'],
    :server_options =>     node[:site]['matching_node']['server']['options'],
    :proxy_options =>      node[:site]['matching_node']['proxy']['options']
  )
end

where matching_node represents a type of node (like Nginx) and site_proxy represents the type of proxy being used for that type of node (like Nexus).

Get template settings from a local file

The template resource can be used to render a template based on settings contained in a local file on disk or to get the settings from a template in a cookbook. Most of the time, the settings are retrieved from a template in a cookbook. The following example shows how the template resource can be used to retrieve these settings from a local file.

The following example is based on a few assumptions:

  • The environment is a Ruby on Rails application that needs render a file named database.yml
  • Information about the application—the user, their password, the server—is stored in a data bag on the Chef server
  • The application is already deployed to the system and that only requirement in this example is to render the database.yml file

The application source tree looks something like:

  myapp/
  -> config/
     -> database.yml.erb

Note

There should not be a file named database.yml (without the .erb), as the database.yml file is what will be rendered using the template resource.

  </div>
</div>

The deployment of the app will end up in /srv, so the full path to this template would be something like /srv/myapp/current/config/database.yml.erb.

The content of the template itself may look like this:

<%= @rails_env %>:
   adapter: <%= @adapter %>
   host: <%= @host %>
   database: <%= @database %>
   username: <%= @username %>
   password: <%= @password %>
   encoding: 'utf8'
   reconnect: true

The recipe will be similar to the following:

results = search(:node, "role:myapp_database_master AND chef_environment:#{node.chef_environment}")
db_master = results[0]

template '/srv/myapp/shared/database.yml' do
  source '/srv/myapp/current/config/database.yml.erb'
  local true
  variables(
    :rails_env => node.chef_environment,
    :adapter => db_master['myapp']['db_adapter'],
    :host => db_master['fqdn'],
    :database => "myapp_#{node.chef_environment}",
    :username => "myapp",
    :password => "SUPERSECRET",
  )
end

where:

  • the search method in the Recipe DSL is used to find the first node that is the database master (of which there should only be one)
  • the :adapter variable property may also require an attribute to have been set on a role, which then determines the correct adapter

The template will render similar to the following:

production:
  adapter: mysql
  host: domU-12-31-39-14-F1-C3.compute-1.internal
  database: myapp_production
  username: myapp
  password: SUPERSECRET
  encoding: utf8
  reconnect: true

This example showed how to use the template resource to render a template based on settings contained in a local file. Some other issues that should be considered when using this type of approach include:

  • Should the database.yml file be in a .gitignore file?
  • How do developers run the application locally?
  • Does this work with chef-solo?

Pass values from recipe to template

The following example shows how pass a value to a template using the variables property in the template resource. The template file is similar to:

[tcpout]
defaultGroup = splunk_indexers_<%= node['splunk']['receiver_port'] %>
disabled=false

[tcpout:splunk_indexers_<%= node['splunk']['receiver_port'] %>]
server=<% @splunk_servers.map  do |s| -%><%= s['ipaddress'] %>:<%= s['splunk']['receiver_port'] %> <% end.join(', ') -%>
<% @outputs_conf.each_pair do |name, value| -%>
<%= name %> = <%= value %>
<% end  -%>

The recipe then uses the variables attribute to find the values for splunk_servers and outputs_conf, before passing them into the template:

template "#{splunk_dir}/etc/system/local/outputs.conf" do
  source 'outputs.conf.erb'
  mode '0755'
  variables :splunk_servers => splunk_servers, :outputs_conf => node['splunk']['outputs_conf']
  notifies :restart, 'service[splunk]'
end

This example can be found in the client.rb recipe and the outputs.conf.erb template files that are located in the chef-splunk cookbook that is maintained by Chef.

timezone resource

timezone resource page

Use the timezone resource to change the system timezone on Windows, Linux, and macOS hosts. Timezones are specified in tz database format, with a complete list of available TZ values for Linux and macOS here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones. On Windows systems run tzutil /l for a complete list of valid timezones.

New in Chef Infra Client 14.6.

Syntax


The full syntax for all of the properties that are available to the timezone resource is:

timezone 'name' do
  timezone      String # default value: 'name' unless specified
  action        Symbol # defaults to :set if not specified
end

where:

  • timezone is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • timezone is the property available to this resource.

Actions


The timezone resource has the following actions:

: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
Set the system timezone.

Properties


The timezone resource has the following properties:

timezone
Ruby Type: String | Default Value: The resource block's name

An optional property to set the timezone value if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the timezone resource in recipes:

Set the timezone to UTC

timezone 'UTC'

Set the timezone to America/Los_Angeles with a friendly resource name on Linux/macOS

timezone 'Set the host's timezone to America/Los_Angeles' do
  timezone 'America/Los_Angeles'
end

Set the timezone to PST with a friendly resource name on Windows

timezone 'Set the host's timezone to PST' do
  timezone 'Pacific Standard time'
end

user resource

user resource page

Use the user resource to add users, update existing users, remove users, and to lock/unlock user passwords.

Note

System attributes are collected by Ohai at the start of every Chef Infra Client run. By design, the actions available to the user resource are processed after the start of a Chef Infra Client run. This means that system attributes added or modified by the user resource during a Chef Infra Client run must be reloaded before they can be available to Chef Infra Client. These system attributes can be reloaded in two ways: by picking up the values at the start of the (next) Chef Infra Client run or by using the ohai resource to reload the system attributes during the current Chef Infra Client run.

Syntax


A user resource block manages users on a node:

user 'a user' do
  comment 'A random user'
  uid 1234
  gid 'groupname'
  home '/home/random'
  shell '/bin/bash'
  password '$1$JJsvHslasdfjVEroftprNn4JHtDi'
end

The full syntax for all of the properties that are available to the user resource is:

user 'name' do
  comment                    String
  force                      true, false # see description
  gid                        String, Integer
  home                       String
  iterations                 Integer
  manage_home                true, false
  non_unique                 true, false
  password                   String
  salt                       String
  shell                      String
  system                     true, false
  uid                        String, Integer
  username                   String # defaults to 'name' if not specified
  action                     Symbol # defaults to :create if not specified
end

where:

  • user is the resource
  • name is the name of the resource block
  • action identifies the steps Chef Infra Client will take to bring the node into the desired state
  • comment, force, gid, home, iterations, manage_home, non_unique, password, salt, shell, system, uid, and username are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The user resource has the following actions:

:create
Default. Create a user with given properties. If a user already exists (but does not match), update that user to match.
:lock
Lock a user’s password.
:manage
Manage an existing user. This action does nothing if the user does not exist.
:modify
Modify an existing user. This action raises an exception if the user does not exist.
:nothing
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 user.
:unlock
Unlock a user’s password.

Properties


The user resource has the following properties:

comment
Ruby Type: String

One (or more) comments about the user.

force
Ruby Type: true, false

Force the removal of a user. May be used only with the :remove action.

Warning

Using this property may leave the system in an inconsistent state. For example, a user account will be removed even if the user is logged in. A user’s home directory will be removed, even if that directory is shared by multiple users.

gid
Ruby Type: String, Integer

The identifier for the group. This property was previously named group and both continue to function.

home
Ruby Type: String

The location of the home directory.

iterations
Ruby Type: Integer

macOS platform only. The number of iterations for a password with a SALTED-SHA512-PBKDF2 shadow hash.

manage_home
Ruby Type: true, false

Manage a user’s home directory.

When used with the :create action, a user’s home directory is created based on HOME_DIR. If the home directory is missing, it is created unless CREATE_HOME in /etc/login.defs is set to no. When created, a skeleton set of files and subdirectories are included within the home directory.

When used with the :modify action, a user’s home directory is moved to HOME_DIR. If the home directory is missing, it is created unless CREATE_HOME in /etc/login.defs is set to no. The contents of the user’s home directory are moved to the new location.

non_unique
Ruby Type: true, false

Create a duplicate (non-unique) user account.

password
Ruby Type: String

The password shadow hash

salt
Ruby Type: String

A SALTED-SHA512-PBKDF2 hash.

shell
Ruby Type: String

The login shell.

system
Ruby Type: true, false

Create a system user. This property may be used with useradd as the provider to create a system user which passes the -r flag to useradd.

uid
Ruby Type: String, Integer

The numeric user identifier.

username
Ruby Type: String

The name of the user. Default value: the name of the resource block. See “Syntax” section above for more information.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the user resource in recipes:

Create a system user

user 'systemguy' do
  comment 'system guy'
  system true
  shell '/bin/false'
end

Create a system user with a variable

The following example shows how to create a system user. In this instance, the home value is calculated and stored in a variable called user_home which sets the user’s home attribute.

user_home = "/home/#{node['cookbook_name']['user']}"

user node['cookbook_name']['user'] do
  gid node['cookbook_name']['group']
  shell '/bin/bash'
  home user_home
  system true
  action :create
end

Use SALTED-SHA512-PBKDF2 passwords

macOS 10.8 (and higher) calculates the password shadow hash using SALTED-SHA512-PBKDF2. The length of the shadow hash value is 128 bytes, the salt value is 32 bytes, and an integer specifies the number of iterations. The following code will calculate password shadow hashes for macOS 10.8 (and higher):

password = 'my_awesome_password'
salt = OpenSSL::Random.random_bytes(32)
iterations = 25000 # Any value above 20k should be fine.

shadow_hash = OpenSSL::PKCS5::pbkdf2_hmac(
  password,
  salt,
  iterations,
  128,
  OpenSSL::Digest::SHA512.new
).unpack('H*').first
salt_value = salt.unpack('H*').first

Use the calculated password shadow hash with the user resource:

user 'my_awesome_user' do
  password 'cbd1a....fc843'  # Length: 256
  salt 'bd1a....fc83'        # Length: 64
  iterations 25000
end

user_ulimit resource

user_ulimit resource page

Use the user_ulimit resource to create individual ulimit files that are installed into the /etc/security/limits.d/ directory.

New in Chef Infra Client 16.0.

Syntax


The full syntax for all of the properties that are available to the user_ulimit resource is:

user_ulimit 'name' do
  core_hard_limit            String, Integer
  core_limit                 String, Integer
  core_soft_limit            String, Integer
  filehandle_hard_limit      String, Integer
  filehandle_limit           String, Integer
  filehandle_soft_limit      String, Integer
  filename                   String
  memory_limit               String, Integer
  process_hard_limit         String, Integer
  process_limit              String, Integer
  process_soft_limit         String, Integer
  rtprio_hard_limit          String, Integer
  rtprio_limit               String, Integer
  rtprio_soft_limit          String, Integer
  stack_hard_limit           String, Integer
  stack_limit                String, Integer
  stack_soft_limit           String, Integer
  username                   String # default value: 'name' unless specified
  virt_limit                 String, Integer
  action                     Symbol # defaults to :create if not specified
end

where:

  • user_ulimit 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.
  • core_hard_limit, core_limit, core_soft_limit, filehandle_hard_limit, filehandle_limit, filehandle_soft_limit, filename, memory_limit, process_hard_limit, process_limit, process_soft_limit, rtprio_hard_limit, rtprio_limit, rtprio_soft_limit, stack_hard_limit, stack_limit, stack_soft_limit, username, and virt_limit are the properties available to this resource.

Actions


The user_ulimit resource has the following actions:

:create
Create a ulimit configuration file
:delete
Delete a ulimit configuration file
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The user_ulimit resource has the following properties:

core_hard_limit
Ruby Type: String, Integer

core_limit
Ruby Type: String, Integer

core_soft_limit
Ruby Type: String, Integer

filehandle_hard_limit
Ruby Type: String, Integer

filehandle_limit
Ruby Type: String, Integer

filehandle_soft_limit
Ruby Type: String, Integer

filename
Ruby Type: String | Default Value: lazy default

memory_limit
Ruby Type: String, Integer

process_hard_limit
Ruby Type: String, Integer

process_limit
Ruby Type: String, Integer

process_soft_limit
Ruby Type: String, Integer

rtprio_hard_limit
Ruby Type: String, Integer

rtprio_limit
Ruby Type: String, Integer

rtprio_soft_limit
Ruby Type: String, Integer

stack_hard_limit
Ruby Type: String, Integer

stack_limit
Ruby Type: String, Integer

stack_soft_limit
Ruby Type: String, Integer

username
Ruby Type: String | Default Value: The resource block's name

virt_limit
Ruby Type: String, Integer


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the user_ulimit resource in recipes:

Set filehandle limit for the tomcat user:

user_ulimit 'tomcat' do
  filehandle_limit 8192
end

Specify a username that differs from the name given to the resource block:

user_ulimit 'Bump filehandle limits for tomcat user' do
  username 'tomcat'
  filehandle_limit 8192
end

Set filehandle limit for the tomcat user with a non-default filename:

user_ulimit 'tomcat' do
  filehandle_limit 8192
  filename 'tomcat_filehandle_limits.conf'
end

windows_ad_join resource

windows_ad_join resource page

Use the windows_ad_join resource to join a Windows Active Directory domain.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_ad_join resource is:

windows_ad_join 'name' do
  domain_name          String # default value: 'name' unless specified
  domain_password      String
  domain_user          String
  new_hostname         String
  ou_path              String
  reboot               Symbol # default value: :immediate
  reboot_delay         Integer # default value: 0
  sensitive            true, false # default value: true
  workgroup_name       String
  action               Symbol # defaults to :join if not specified
end

where:

  • windows_ad_join is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • domain_name, domain_password, domain_user, new_hostname, ou_path, reboot, reboot_delay, sensitive, and workgroup_name are the properties available to this resource.

Actions


The windows_ad_join resource has the following actions:

:join
Default. Join the Active Directory domain.
:leave
Leave an Active Directory domain and re-join a workgroup.
: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 windows_ad_join resource has the following properties:

domain_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the FQDN of the Active Directory domain to join if it differs from the resource block’s name.

domain_password
Ruby Type: String | REQUIRED

The password for the domain user. Note that this resource is set to hide sensitive information by default.

domain_user
Ruby Type: String | REQUIRED

The domain user that will be used to join the domain.

new_hostname
Ruby Type: String

Specifies a new hostname for the computer in the new domain.

New in Chef Client 14.5

ou_path
Ruby Type: String

The path to the Organizational Unit where the host will be placed.

reboot
Ruby Type: Symbol | Default Value: :immediate
Allowed Values: :delayed, :immediate, :never, :reboot_now, :request_reboot

Controls the system reboot behavior post domain joining. Reboot immediately, after the Chef Infra Client run completes, or never. Note that a reboot is necessary for changes to take effect.

reboot_delay
Ruby Type: Integer | Default Value: 0

The amount of time (in minutes) to delay a reboot request.

New in Chef Infra Client 16.5

sensitive
Ruby Type: true, false | Default Value: true

workgroup_name
Ruby Type: String

Specifies the name of a workgroup to which the computer is added to when it is removed from the domain. The default value is WORKGROUP. This property is only applicable to the :leave action.

New in Chef Infra Client 15.4


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_ad_join resource in recipes:

Join a domain

windows_ad_join 'ad.example.org' do
  domain_user 'nick'
  domain_password 'p@ssw0rd1'
end

Join a domain, as win-workstation

windows_ad_join 'ad.example.org' do
  domain_user 'nick'
  domain_password 'p@ssw0rd1'
  new_hostname 'win-workstation'
end

Leave the current domain and re-join the local workgroup

windows_ad_join 'Leave domain' do
  action :leave
  workgroup 'local'
end

windows_audit_policy resource

windows_audit_policy resource page

Use the windows_audit_policy resource to configure system level and per-user Windows advanced audit policy settings.

New in Chef Infra Client 16.2.

Syntax


The full syntax for all of the properties that are available to the windows_audit_policy resource is:

windows_audit_policy 'name' do
  audit_base_directories       true, false
  audit_base_objects           true, false
  crash_on_audit_fail          true, false
  exclude_user                 String
  failure                      true, false
  full_privilege_auditing      true, false
  include_user                 String
  subcategory                  String, Array
  success                      true, false
  action                       Symbol # defaults to :set if not specified
end

where:

  • windows_audit_policy 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.
  • audit_base_directories, audit_base_objects, crash_on_audit_fail, exclude_user, failure, full_privilege_auditing, include_user, subcategory, and success are the properties available to this resource.

Actions


The windows_audit_policy 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
Configure an audit policy.

Properties


The windows_audit_policy resource has the following properties:

audit_base_directories
Ruby Type: true, false

Setting this audit policy option to true will force the system to assign a System Access Control List to named objects to enable auditing of container objects such as directories.

audit_base_objects
Ruby Type: true, false

Setting this audit policy option to true will force the system to assign a System Access Control List to named objects to enable auditing of base objects such as mutexes.

crash_on_audit_fail
Ruby Type: true, false

Setting this audit policy option to true will cause the system to crash if the auditing system is unable to log events.

exclude_user
Ruby Type: String

The audit policy specified by the category or subcategory is applied per-user if specified. When a user is specified, exclude user. Include and exclude cannot be used at the same time.

failure
Ruby Type: true, false

Specify failure auditing. By setting this property to true the resource will enable failure for the category or sub category. Success is the default and is applied if neither success nor failure are specified.

full_privilege_auditing
Ruby Type: true, false

Setting this audit policy option to true will force the audit of all privilege changes except SeAuditPrivilege. Setting this property may cause the logs to fill up more quickly.

include_user
Ruby Type: String

The audit policy specified by the category or subcategory is applied per-user if specified. When a user is specified, include user. Include and exclude cannot be used at the same time.

subcategory
Ruby Type: String, Array

The audit policy subcategory, specified by GUID or name. Applied system-wide if no user is specified.

success
Ruby Type: true, false

Specify success auditing. By setting this property to true the resource will enable success for the category or sub category. Success is the default and is applied if neither success nor failure are specified.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_audit_policy resource in recipes:

Set Logon and Logoff policy to “Success and Failure”:

windows_audit_policy "Set Audit Policy for 'Logon and Logoff' actions to 'Success and Failure'" do
  subcategory %w(Logon Logoff)
  success true
  failure true
  action :set
end

Set Credential Validation policy to “Success”:

windows_audit_policy "Set Audit Policy for 'Credential Validation' actions to 'Success'" do
  subcategory  'Credential Validation'
  success true
  failure false
  action :set
end

Enable CrashOnAuditFail option:

windows_audit_policy 'Enable CrashOnAuditFail option' do
  crash_on_audit_fail true
  action :set
end

windows_auto_run resource

windows_auto_run resource page

Use the windows_auto_run resource to set applications to run at login.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_auto_run resource is:

windows_auto_run 'name' do
  args              String
  path              String
  program_name      String # default value: 'name' unless specified
  root              Symbol # default value: :machine
  action            Symbol # defaults to :create if not specified
end

where:

  • windows_auto_run is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • args, path, program_name, and root are the properties available to this resource.

Actions


The windows_auto_run resource has the following actions:

:create
Create an item to be run at login.
: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
Remover an item that was previously configured to run at login.

Properties


The windows_auto_run resource has the following properties:

args
Ruby Type: String

Any arguments to be used with the program.

path
Ruby Type: String

The path to the program that will run at login.

program_name
Ruby Type: String | Default Value: The resource block's name

The name of the program to run at login if it differs from the resource block’s name.

root
Ruby Type: Symbol | Default Value: :machine
Allowed Values: :machine, :user

The registry root key to put the entry under.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_auto_run resource in recipes:

Run BGInfo at login

windows_auto_run 'BGINFO' do
  program 'C:/Sysinternals/bginfo.exe'
  args    ''C:/Sysinternals/Config.bgi' /NOLICPROMPT /TIMER:0'
  action  :create
end

windows_certificate resource

windows_certificate resource page

Use the windows_certificate resource to install a certificate into the Windows certificate store from a file. The resource grants read-only access to the private key for designated accounts. Due to current limitations in WinRM, installing certificates remotely may not work if the operation requires a user profile. Operations on the local machine store should still work.

New in Chef Infra Client 14.7.

Syntax


The full syntax for all of the properties that are available to the windows_certificate resource is:

windows_certificate 'name' do
  cert_path            String
  pfx_password         String
  private_key_acl      Array
  source               String # default value: 'name' unless specified
  store_name           String # default value: "MY"
  user_store           true, false # default value: false
  action               Symbol # defaults to :create if not specified
end

where:

  • windows_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_path, pfx_password, private_key_acl, source, store_name, and user_store are the properties available to this resource.

Actions


The windows_certificate resource has the following actions:

:acl_add
Adds read-only entries to a certificate’s private key ACL.
:create
Creates or updates a certificate.
:delete
Deletes a certificate.
:fetch
Fetches a certificate.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:verify
Verifies a certificate.

Properties


The windows_certificate resource has the following properties:

cert_path
Ruby Type: String

pfx_password
Ruby Type: String

The password to access the source if it is a pfx file.

private_key_acl
Ruby Type: Array

An array of ‘domainccount’ entries to be granted read-only access to the certificate’s private key. Not idempotent.

source
Ruby Type: String | Default Value: The resource block's name

The source file (for create and acl_add), thumbprint (for delete and acl_add) or subject (for delete) if it differs from the resource block’s name.

store_name
Ruby Type: String | Default Value: MY
Allowed Values: "AUTHROOT", "CA", "CLIENTAUTHISSUER", "DISALLOWED", "MY", "REMOTE DESKTOP", "ROOT", "SMARTCARDROOT", "TRUST", "TRUSTEDDEVICES", "TRUSTEDPEOPLE", "TRUSTEDPUBLISHER", "TrustedPublisher", "WEBHOSTING"

The certificate store to manipulate.

user_store
Ruby Type: true, false | Default Value: false

Use the user store of the local machine store if set to false.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_certificate resource in recipes:

Add PFX cert to local machine personal store and grant accounts read-only access to private key

windows_certificate 'c:/test/mycert.pfx' do
  pfx_password 'password'
  private_key_acl ["acme\fred", "pc\jane"]
end

Add cert to trusted intermediate store

windows_certificate 'c:/test/mycert.cer' do
  store_name 'CA'
end

Remove all certificates matching the subject

windows_certificate 'me.acme.com' do
  action :delete
end

windows_dfs_folder resource

windows_dfs_folder resource page

Use the windows_dfs_folder resource to creates a folder within DFS as many levels deep as required.

New in Chef Infra Client 15.0.

Syntax


The full syntax for all of the properties that are available to the windows_dfs_folder resource is:

windows_dfs_folder 'name' do
  description         String
  folder_path         String # default value: 'name' unless specified
  namespace_name      String
  target_path         String
  action              Symbol # defaults to :create if not specified
end

where:

  • windows_dfs_folder 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.
  • description, folder_path, namespace_name, and target_path are the properties available to this resource.

Actions


The windows_dfs_folder resource has the following actions:

:create
Creates the folder in dfs namespace. Default.
:delete
Deletes the folder in the dfs namespace.
: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 windows_dfs_folder resource has the following properties:

description
Ruby Type: String

Description for the share.

folder_path
Ruby Type: String | Default Value: The resource block's name

An optional property to set the path of the dfs folder if it differs from the resource block’s name.

namespace_name
Ruby Type: String | REQUIRED

The namespace this should be created within.

target_path
Ruby Type: String

The target that this path will connect you to.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

windows_dfs_namespace resource

windows_dfs_namespace resource page

Use the windows_dfs_namespace resource to creates a share and DFS namespace on a Windows server.

New in Chef Infra Client 15.0.

Syntax


The full syntax for all of the properties that are available to the windows_dfs_namespace resource is:

windows_dfs_namespace 'name' do
  change_users        Array # default value: []
  description         String
  full_users          Array # default value: ["BUILTIN\\administrators"]
  namespace_name      String # default value: 'name' unless specified
  read_users          Array # default value: []
  root                String # default value: "C:\\DFSRoots"
  action              Symbol # defaults to :create if not specified
end

where:

  • windows_dfs_namespace 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.
  • change_users, description, full_users, namespace_name, read_users, and root are the properties available to this resource.

Actions


The windows_dfs_namespace resource has the following actions:

:create
Creates the dfs namespace on the server. Default.
:delete
Deletes a DFS Namespace including the directory on disk.
: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 windows_dfs_namespace resource has the following properties:

change_users
Ruby Type: Array | Default Value: []

Determines which users should have change access to the share.

description
Ruby Type: String | REQUIRED

Description of the share.

full_users
Ruby Type: Array | Default Value: ["BUILTIN\\administrators"]

Determines which users should have full access to the share.

namespace_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the dfs namespace if it differs from the resource block’s name.

read_users
Ruby Type: Array | Default Value: []

Determines which users should have read access to the share.

root
Ruby Type: String | Default Value: C:\DFSRoots

The root from which to create the DFS tree. Defaults to C:\DFSRoots.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

windows_dfs_server resource

windows_dfs_server resource page

Use the windows_dfs_server resource to set system-wide DFS settings.

New in Chef Infra Client 15.0.

Syntax


The full syntax for all of the properties that are available to the windows_dfs_server resource is:

windows_dfs_server 'name' do
  enable_site_costed_referrals      true, false # default value: false
  ldap_timeout_secs                 Integer # default value: 30
  prefer_login_dc                   true, false # default value: false
  sync_interval_secs                Integer # default value: 3600
  use_fqdn                          true, false # default value: false
  action                            Symbol # defaults to :configure if not specified
end

where:

  • windows_dfs_server 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.
  • enable_site_costed_referrals, ldap_timeout_secs, prefer_login_dc, sync_interval_secs, and use_fqdn are the properties available to this resource.

Actions


The windows_dfs_server resource has the following actions:

:configure
Configure DFS settings
: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 windows_dfs_server resource has the following properties:

enable_site_costed_referrals
Ruby Type: true, false | Default Value: false

ldap_timeout_secs
Ruby Type: Integer | Default Value: 30

prefer_login_dc
Ruby Type: true, false | Default Value: false

sync_interval_secs
Ruby Type: Integer | Default Value: 3600

use_fqdn
Ruby Type: true, false | Default Value: false

Indicates whether a DFS namespace server uses FQDNs in referrals. If this property is set to true, the server uses FQDNs in referrals. If this property is set to false then the server uses NetBIOS names.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

windows_dns_record resource

windows_dns_record resource page

The windows_dns_record resource creates a DNS record for the given domain.

New in Chef Infra Client 15.0.

Syntax


The full syntax for all of the properties that are available to the windows_dns_record resource is:

windows_dns_record 'name' do
  dns_server       String # default value: "localhost"
  record_name      String # default value: 'name' unless specified
  record_type      String # default value: "ARecord"
  target           String
  zone             String
  action           Symbol # defaults to :create if not specified
end

where:

  • windows_dns_record 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.
  • dns_server, record_name, record_type, target, and zone are the properties available to this resource.

Actions


The windows_dns_record resource has the following actions:

:create
Creates and updates the DNS entry.
:delete
Deletes a DNS entry.
: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 windows_dns_record resource has the following properties:

dns_server
Ruby Type: String | Default Value: localhost

The name of the DNS server on which to create the record.

New in Chef Infra Client 16.3

record_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the dns record name if it differs from the resource block’s name.

record_type
Ruby Type: String | Default Value: ARecord
Allowed Values: "ARecord", "CNAME", "PTR"

The type of record to create, can be either ARecord, CNAME or PTR.

target
Ruby Type: String | REQUIRED

The target for the record.

zone
Ruby Type: String | REQUIRED

The zone to create the record in.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

windows_dns_zone resource

windows_dns_zone resource page

The windows_dns_zone resource creates an Active Directory Integrated DNS Zone on the local server.

New in Chef Infra Client 15.0.

Syntax


The full syntax for all of the properties that are available to the windows_dns_zone resource is:

windows_dns_zone 'name' do
  replication_scope      String # default value: "Domain"
  server_type            String # default value: "Domain"
  zone_name              String # default value: 'name' unless specified
  action                 Symbol # defaults to :create if not specified
end

where:

  • windows_dns_zone 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.
  • replication_scope, server_type, and zone_name are the properties available to this resource.

Actions


The windows_dns_zone resource has the following actions:

:create
Creates and updates a DNS Zone. Default.
:delete
Deletes a DNS Zone.
: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 windows_dns_zone resource has the following properties:

replication_scope
Ruby Type: String | Default Value: Domain

The replication scope for the zone, required if server_type set to ‘Domain’.

server_type
Ruby Type: String | Default Value: Domain
Allowed Values: "Domain", "Standalone"

The type of DNS server, Domain or Standalone.

zone_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the dns zone name if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


This resource does not have any examples.

windows_env resource

windows_env resource page

Use the windows_env resource to manage environment keys in Microsoft Windows. After an environment key is set, Microsoft Windows must be restarted before the environment key will be available to the Task Scheduler.

This resource was previously called the env resource; its name was updated in Chef Client 14.0 to reflect the fact that only Windows is supported. Existing cookbooks using env will continue to function, but should be updated to use the new name.

Note

On UNIX-based systems, the best way to manipulate environment keys is with the ENV variable in Ruby; however, this approach does not have the same permanent effect as using the windows_env resource.

Syntax


The full syntax for all of the properties that are available to the windows_env resource is:

windows_env 'name' do
  delim         String, false
  key_name      String # default value: 'name' unless specified
  user          String # default value: "<System>"
  value         String
  action        Symbol # defaults to :create if not specified
end

where:

  • windows_env is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • delim, key_name, user, and value are the properties available to this resource.

Actions


The windows_env resource has the following actions:

:create
Default. Create an environment variable. If an environment variable already exists (but does not match), update that environment variable to match.
:delete
Delete an environment variable.
:modify
Modify an existing environment variable. This prepends the new value to the existing value, using the delimiter specified by the delim property.
:nothing
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 windows_env resource has the following properties:

delim
Ruby Type: String, false

The delimiter that is used to separate multiple values for a single key.

key_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the name of the key that is to be created, deleted, or modified if it differs from the resource block’s name.

user
Ruby Type: String | Default Value: <System>

value
Ruby Type: String | REQUIRED

The value of the environmental variable to set.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_env resource in recipes:

Set an environment variable:

windows_env 'ComSpec' do
  value 'C:\Windows\system32\cmd.exe'
end

windows_feature resource

windows_feature resource page

Use the windows_feature resource to add, remove or entirely delete Windows features and roles. This resource calls the windows_feature_dism or windows_feature_powershell resources depending on the specified installation method, and defaults to DISM, which is available on both Workstation and Server editions of Windows.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_feature resource is:

windows_feature 'name' do
  all                   true, false # default value: false
  feature_name          Array, String # default value: 'name' unless specified
  install_method        Symbol # default value: :windows_feature_dism
  management_tools      true, false # default value: false
  source                String
  timeout               Integer # default value: 600
  action                Symbol # defaults to :install if not specified
end

where:

  • windows_feature is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • all, feature_name, install_method, management_tools, source, and timeout are the properties available to this resource.

Actions


The windows_feature resource has the following actions:

:delete
Delete a Windows role / feature from the image using PowerShell.
:install
Default. Install a Windows role / feature using PowerShell.
: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 role / feature using PowerShell.

Properties


The windows_feature resource has the following properties:

all
Ruby Type: true, false | Default Value: false

Install all sub-features.

feature_name
Ruby Type: Array, String | Default Value: The resource block's name

The name of the feature(s) or role(s) to install if they differ from the resource block’s name. The same feature may have different names depending on the underlying installation method being used (ie DHCPServer vs DHCP; DNS-Server-Full-Role vs DNS).

install_method
Ruby Type: Symbol | Default Value: :windows_feature_dism
Allowed Values: :windows_feature_dism, :windows_feature_powershell, :windows_feature_servermanagercmd

The underlying installation method to use for feature installation. Specify :windows_feature_dism for DISM or :windows_feature_powershell for PowerShell.

management_tools
Ruby Type: true, false | Default Value: false

Install all applicable management tools for the roles, role services, or features (PowerShell-only).

source
Ruby Type: String

Specify a local repository for the feature install.

timeout
Ruby Type: Integer | Default Value: 600

Specifies a timeout (in seconds) for the feature installation.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_feature resource in recipes:

Install the DHCP Server feature:

windows_feature 'DHCPServer' do
  action :install
end

Install the .Net 3.5.1 feature using repository files on DVD:

windows_feature "NetFx3" do
  action :install
  source 'd:\sources\sxs'
end

Remove Telnet Server and Client features:

windows_feature %w(TelnetServer TelnetClient) do
  action :remove
end

Add the SMTP Server feature using the PowerShell provider:

windows_feature 'smtp-server' do
  action :install
  all true
  install_method :windows_feature_powershell
end

Install multiple features using one resource with the PowerShell provider:

windows_feature %w(Web-Asp-Net45 Web-Net-Ext45) do
  action :install
  install_method :windows_feature_powershell
end

Install the Network Policy and Access Service feature, including the management tools:

windows_feature 'NPAS' do
  action :install
  management_tools true
  install_method :windows_feature_powershell
end

windows_feature_dism resource

windows_feature_dism resource page

Use the windows_feature_dism resource to add, remove, or entirely delete Windows features and roles using DISM.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_feature_dism resource is:

windows_feature_dism 'name' do
  all               true, false # default value: false
  feature_name      Array, String # default value: 'name' unless specified
  source            String
  timeout           Integer # default value: 600
  action            Symbol # defaults to :install if not specified
end

where:

  • windows_feature_dism is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • all, feature_name, source, and timeout are the properties available to this resource.

Actions


The windows_feature_dism resource has the following actions:

:delete
Delete a Windows role / feature from the image using DISM.
:install
Default. Install a Windows role / feature using DISM.
: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 role / feature using DISM.

Properties


The windows_feature_dism resource has the following properties:

all
Ruby Type: true, false | Default Value: false

Install all sub-features. When set to true, this is the equivalent of specifying the /All switch to dism.exe

feature_name
Ruby Type: Array, String | Default Value: The resource block's name

The name of the feature(s) or role(s) to install if they differ from the resource name.

source
Ruby Type: String

Specify a local repository for the feature install.

timeout
Ruby Type: Integer | Default Value: 600

Specifies a timeout (in seconds) for the feature installation.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_feature_dism resource in recipes:

Installing the TelnetClient service:

windows_feature_dism "TelnetClient"

Installing two features by using an array:

windows_feature_dism %w(TelnetClient TFTP)

windows_feature_powershell resource

windows_feature_powershell resource page

Use the windows_feature_powershell resource to add, remove, or entirely delete Windows features and roles using PowerShell. This resource offers significant speed benefits over the windows_feature_dism resource, but requires installation of the Remote Server Administration Tools on non-server releases of Windows.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_feature_powershell resource is:

windows_feature_powershell 'name' do
  all                   true, false # default value: false
  feature_name          Array, String # default value: 'name' unless specified
  management_tools      true, false # default value: false
  source                String
  timeout               Integer # default value: 600
  action                Symbol # defaults to :install if not specified
end

where:

  • windows_feature_powershell 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.
  • all, feature_name, management_tools, source, and timeout are the properties available to this resource.

Actions


The windows_feature_powershell resource has the following actions:

:delete
Delete a Windows role / feature from the image using PowerShell.
:install
Default. Install a Windows role / feature using PowerShell.
: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 role / feature using PowerShell.

Properties


The windows_feature_powershell resource has the following properties:

all
Ruby Type: true, false | Default Value: false

Install all subfeatures. When set to true, this is the equivalent of specifying the -InstallAllSubFeatures switch with Add-WindowsFeature.

feature_name
Ruby Type: Array, String | Default Value: The resource block's name

The name of the feature(s) or role(s) to install if they differ from the resource block’s name.

management_tools
Ruby Type: true, false | Default Value: false

Install all applicable management tools for the roles, role services, or features.

source
Ruby Type: String

Specify a local repository for the feature install.

timeout
Ruby Type: Integer | Default Value: 600

Specifies a timeout (in seconds) for the feature installation.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_feature_powershell resource in recipes:

Add the SMTP Server feature:

windows_feature_powershell "smtp-server" do
  action :install
  all true
end

Install multiple features using one resource:

windows_feature_powershell ['Web-Asp-Net45', 'Web-Net-Ext45'] do
  action :install
end

Install the Network Policy and Access Service feature:

windows_feature_powershell 'NPAS' do
  action :install
  management_tools true
end

windows_firewall_profile resource

windows_firewall_profile resource page

Use the windows_firewall_profile resource to enable, disable, and configure the Windows firewall.

New in Chef Infra Client 16.3.

Syntax


The full syntax for all of the properties that are available to the windows_firewall_profile resource is:

windows_firewall_profile 'name' do
  allow_inbound_rules             true, false, String
  allow_local_firewall_rules      true, false, String
  allow_local_ipsec_rules         true, false, String
  allow_unicast_response          true, false, String
  allow_user_apps                 true, false, String
  allow_user_ports                true, false, String
  default_inbound_action          String
  default_outbound_action         String
  display_notification            true, false, String
  profile                         String # default value: 'name' unless specified
  action                          Symbol # defaults to :enable if not specified
end

where:

  • windows_firewall_profile 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.
  • allow_inbound_rules, allow_local_firewall_rules, allow_local_ipsec_rules, allow_unicast_response, allow_user_apps, allow_user_ports, default_inbound_action, default_outbound_action, display_notification, and profile are the properties available to this resource.

Actions


The windows_firewall_profile resource has the following actions:

:disable
Disable a Windows Firewall profile
:enable
Enable and optionally configure a Windows Firewall profile
: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 windows_firewall_profile resource has the following properties:

allow_inbound_rules
Ruby Type: true, false, String
Allowed Values: true, false, "NotConfigured"

Allow users to set inbound firewall rules

allow_local_firewall_rules
Ruby Type: true, false, String
Allowed Values: true, false, "NotConfigured"

Merges inbound firewall rules into the policy

allow_local_ipsec_rules
Ruby Type: true, false, String
Allowed Values: true, false, "NotConfigured"

Allow users to manage local connection security rules

allow_unicast_response
Ruby Type: true, false, String
Allowed Values: true, false, "NotConfigured"

Allow unicast responses to multicast and broadcast messages

allow_user_apps
Ruby Type: true, false, String
Allowed Values: true, false, "NotConfigured"

Allow user applications to manage firewall

allow_user_ports
Ruby Type: true, false, String
Allowed Values: true, false, "NotConfigured"

Allow users to manage firewall port rules

default_inbound_action
Ruby Type: String
Allowed Values: "Allow", "Block", "NotConfigured"

Set the default policy for inbound network traffic

default_outbound_action
Ruby Type: String
Allowed Values: "Allow", "Block", "NotConfigured"

Set the default policy for outbound network traffic

display_notification
Ruby Type: true, false, String
Allowed Values: true, false, "NotConfigured"

Display a notification when firewall blocks certain activity

profile
Ruby Type: String | Default Value: The resource block's name
Allowed Values: "Domain", "Private", "Public"

Set the Windows Profile being configured


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_firewall_profile resource in recipes:

Enable and Configure the Private Profile of the Windows Profile:

windows_firewall_profile 'Private' do
  default_inbound_action 'Block'
  default_outbound_action 'Allow'
  allow_inbound_rules true
  display_notification false
  action :enable
end

Enable and Configure the Public Profile of the Windows Firewall:

windows_firewall_profile 'Public' do
  default_inbound_action 'Block'
  default_outbound_action 'Allow'
  allow_inbound_rules false
  display_notification false
  action :enable
end

Disable the Domain Profile of the Windows Firewall:

windows_firewall_profile 'Disable the Domain Profile of the Windows Firewall' do
  profile 'Domain'
  action :disable
end

windows_firewall_rule resource

windows_firewall_rule resource page

Use the windows_firewall_rule resource to create, change or remove Windows firewall rules.

New in Chef Infra Client 14.7.

Syntax


The full syntax for all of the properties that are available to the windows_firewall_rule resource is:

windows_firewall_rule 'name' do
  description          String
  direction            Symbol, String # default value: :inbound
  displayname          String # default value: The rule_name property value.
  enabled              true, false # default value: true
  firewall_action      Symbol, String # default value: :allow
  group                String
  icmp_type            String, Integer # default value: "Any"
  interface_type       Symbol, String # default value: :any
  local_address        String
  local_port           String, Integer, Array
  profile              Symbol, String, Array # default value: :any
  program              String
  protocol             String # default value: "TCP"
  remote_address       String
  remote_port          String, Integer, Array
  rule_name            String # default value: 'name' unless specified
  service              String
  action               Symbol # defaults to :create if not specified
end

where:

  • windows_firewall_rule 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.
  • description, direction, displayname, enabled, firewall_action, group, icmp_type, interface_type, local_address, local_port, profile, program, protocol, remote_address, remote_port, rule_name, and service are the properties available to this resource.

Actions


The windows_firewall_rule resource has the following actions:

:create
Create a Windows firewall entry.
:delete
Delete an existing Windows firewall entry.
: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 windows_firewall_rule resource has the following properties:

description
Ruby Type: String

The description to assign to the firewall rule.

direction
Ruby Type: Symbol, String | Default Value: :inbound
Allowed Values: :inbound, :outbound

The direction of the firewall rule. Direction means either inbound or outbound traffic.

displayname
Ruby Type: String | Default Value: The rule_name property value.

The displayname to assign to the firewall rule.

New in Chef Infra Client 16.0

enabled
Ruby Type: true, false | Default Value: true

Whether or not to enable the firewall rule.

firewall_action
Ruby Type: Symbol, String | Default Value: :allow
Allowed Values: :allow, :block, :notconfigured

The action of the firewall rule.

group
Ruby Type: String

Specifies that only matching firewall rules of the indicated group association are copied.

New in Chef Infra Client 16.0

icmp_type
Ruby Type: String, Integer | Default Value: Any

Specifies the ICMP Type parameter for using a protocol starting with ICMP

New in Chef Infra Client 16.0

interface_type
Ruby Type: Symbol, String | Default Value: :any
Allowed Values: :any, :remoteaccess, :wired, :wireless

The interface type the firewall rule applies to.

local_address
Ruby Type: String

The local address the firewall rule applies to.

local_port
Ruby Type: String, Integer, Array

The local port the firewall rule applies to.

profile
Ruby Type: Symbol, String, Array | Default Value: :any

The profile the firewall rule applies to.

program
Ruby Type: String

The program the firewall rule applies to.

protocol
Ruby Type: String | Default Value: TCP

The protocol the firewall rule applies to.

remote_address
Ruby Type: String

The remote address the firewall rule applies to.

remote_port
Ruby Type: String, Integer, Array

The remote port the firewall rule applies to.

rule_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the name of the firewall rule to assign if it differs from the resource block’s name.

service
Ruby Type: String

The service the firewall rule applies to.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_firewall_rule resource in recipes:

Allowing port 80 access:

windows_firewall_rule 'IIS' do
  local_port '80'
  protocol 'TCP'
  firewall_action :allow
end

Allow protocol ICMPv6 with ICMP Type:

windows_firewall_rule 'CoreNet-Rule' do
  rule_name 'CoreNet-ICMP6-LR2-In'
  display_name 'Core Networking - Multicast Listener Report v2 (ICMPv6-In)'
  local_port 'RPC'
  protocol 'ICMPv6'
  icmp_type '8'
end

Blocking WinRM over HTTP on a particular IP:

windows_firewall_rule 'Disable WinRM over HTTP' do
  local_port '5985'
  protocol 'TCP'
  firewall_action :block
  local_address '192.168.1.1'
end

Deleting an existing rule

windows_firewall_rule 'Remove the SSH rule' do
  rule_name 'ssh'
  action :delete
end

windows_font resource

windows_font resource page

Use the windows_font resource to install font files on Windows. By default, the font is sourced from the cookbook using the resource, but a URI source can be specified as well.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_font resource is:

windows_font 'name' do
  font_name      String # default value: 'name' unless specified
  source         String
  action         Symbol # defaults to :install if not specified
end

where:

  • windows_font is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • font_name and source are the properties available to this resource.

Actions


The windows_font resource has the following actions:

:install
Default. Install the font to the system fonts directory.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.

Properties


The windows_font resource has the following properties:

font_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the name of the font to install if it differs from the resource block’s name.

source
Ruby Type: String

A local filesystem path or URI that is used to source the font file.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_font resource in recipes:

Install a font from a https source:

windows_font 'Custom.otf' do
  source "https://example.com/Custom.otf"
end

windows_package resource

windows_package resource page

Use the windows_package resource to manage Microsoft Installer Package (MSI) packages for the Microsoft Windows platform.

Syntax


A windows_package resource block manages a package on a node, typically by installing it. The simplest use of the windows_package resource is:

windows_package 'package_name'

which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the windows_package resource is:

windows_package 'name' do
  checksum                    String
  installer_type              Symbol
  options                     String
  package_name                String
  remote_file_attributes      Hash
  returns                     String, Integer, Array
  source                      String # default value: "The resource block's name"
  timeout                     String, Integer # default value: "600 (seconds)"
  version                     String
  action                      Symbol # defaults to :install if not specified
end

where:

  • windows_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • checksum, installer_type, options, package_name, remote_file_attributes, returns, source, timeout, and version are the properties available to this resource.

Actions


The windows_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.
:remove
Remove a package.

Properties


The windows_package resource has the following properties:

checksum
Ruby Type: String

The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, Chef Infra Client does not download it. Use when a URL is specified by the source property.

installer_type
Ruby Type: Symbol
Allowed Values: :custom, :inno, :installshield, :msi, :nsis, :wise

A symbol that specifies the type of package. Possible values: :custom (such as installing a non-.msi file that embeds an .msi-based installer), :inno (Inno Setup), :installshield (InstallShield), :msi (Microsoft Installer Package (MSI)), :nsis (Nullsoft Scriptable Install System (NSIS)), :wise (Wise).

options
Ruby Type: String

One (or more) additional 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.

remote_file_attributes
Ruby Type: Hash

This property allows you to define a hash of properties and their value if the source package to be installed is at a remote location. This hash will be used by the underlying remote_file resource which will fetch the source package.

returns
Ruby Type: String, Integer, Array of integers | Default Value: 0 (success) and 3010 (success where a reboot is necessary)

A comma-delimited list of return codes that indicate the success or failure of the package command that was run.

source
Ruby Type: String | Default Value: The resource block's name

The path to a package in the local file system. The location of the package may be at a URL.

If the source property is not specified, the package name MUST be exactly the same as the display name found in Add/Remove programs or exactly the same as the DisplayName property in the appropriate registry key, which may be one of the following:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

Note

If there are multiple versions of a package installed with the same display name, all of those packages will be removed unless a version is provided in the version property or unless it can be discovered in the installer file specified by the source property.

timeout
Ruby Type: String, Integer | Default Value: 600 (seconds)

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String

The version of a package to be installed or upgraded.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_package resource in recipes:

Install a package:

windows_package '7zip' do
  action :install
  source 'C:\7z920.msi'
end

Specify a URL for the source attribute:

windows_package '7zip' do
  source 'http://www.7-zip.org/a/7z938-x64.msi'
end

Specify path and checksum:

windows_package '7zip' do
  source 'http://www.7-zip.org/a/7z938-x64.msi'
  checksum '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3'
end

Modify remote_file resource attributes:

The windows_package resource may specify a package at a remote location using the remote_file_attributes property. This uses the remote_file resource to download the contents at the specified URL and passes in a Hash that modifies the properties of the remote_file resource.

windows_package '7zip' do
  source 'http://www.7-zip.org/a/7z938-x64.msi'
  remote_file_attributes ({
    :path => 'C:\7zip.msi',
    :checksum => '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3'
  })
end

Download a nsis (Nullsoft) package resource:

windows_package 'Mercurial 3.6.1 (64-bit)' do
  source 'http://mercurial.selenic.com/release/windows/Mercurial-3.6.1-x64.exe'
  checksum 'febd29578cb6736163d232708b834a2ddd119aa40abc536b2c313fc5e1b5831d'
end

Download a custom package:

windows_package 'Microsoft Visual C++ 2005 Redistributable' do
  source 'https://download.microsoft.com/download/6/B/B/6BB661D6-A8AE-4819-B79F-236472F6070C/vcredist_x86.exe'
  installer_type :custom
  options '/Q'
end

windows_pagefile resource

windows_pagefile resource page

Use the windows_pagefile resource to configure pagefile settings on Windows.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_pagefile resource is:

windows_pagefile 'name' do
  automatic_managed      true, false # default value: false
  initial_size           Integer
  maximum_size           Integer
  path                   String # default value: 'name' unless specified
  system_managed         true, false
  action                 Symbol # defaults to :set if not specified
end

where:

  • windows_pagefile is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • automatic_managed, initial_size, maximum_size, path, and system_managed are the properties available to this resource.

Actions


The windows_pagefile resource has the following actions:

:delete
Deletes the specified pagefile.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:set
Default. Configures the default pagefile, creating it if it doesn’t exist.

Properties


The windows_pagefile resource has the following properties:

automatic_managed
Ruby Type: true, false | Default Value: false

Enable automatic management of pagefile initial and maximum size. Setting this to true ignores initial_size and maximum_size properties.

initial_size
Ruby Type: Integer

Initial size of the pagefile in megabytes.

maximum_size
Ruby Type: Integer

Maximum size of the pagefile in megabytes.

path
Ruby Type: String | Default Value: The resource block's name

An optional property to set the pagefile name if it differs from the resource block’s name.

system_managed
Ruby Type: true, false

Configures whether the system manages the pagefile size.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_pagefile resource in recipes:

Set the system to manage pagefiles:

windows_pagefile 'Enable automatic management of pagefiles' do
  automatic_managed true
end

Delete a pagefile:

windows_pagefile 'Delete the pagefile' do
  path 'C:pagefile.sys'
  action :delete
end

Create a pagefile with an initial and maximum size:

windows_pagefile 'create the pagefile' do
  path 'C:pagefile.sys'
  initial_size 100
  maximum_size 200
end

windows_path resource

windows_path resource page

Use the windows_path resource to manage the path environment variable on Microsoft Windows.

New in Chef Infra Client 13.4.

Syntax


The full syntax for all of the properties that are available to the windows_path resource is:

windows_path 'name' do
  path      String # default value: 'name' unless specified
  action    Symbol # defaults to :add if not specified
end

where:

  • windows_path is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • path is the property available to this resource.

Actions


The windows_path resource has the following actions:

:add
Add an item to the system path
: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 an item from the system path

Properties


The windows_path resource has the following properties:

path
Ruby Type: String | Default Value: The resource block's name

An optional property to set the path value if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_path resource in recipes:

Add Sysinternals to the system path:

windows_path 'C:\Sysinternals' do
  action :add
end

Remove 7-Zip from the system path:

windows_path 'C:\7-Zip' do
  action :remove
end

windows_printer resource

windows_printer resource page

Use the windows_printer resource to setup Windows printers. Note that this doesn’t currently install a printer driver. You must already have the driver installed on the system.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_printer resource is:

windows_printer 'name' do
  comment           String
  default           true, false # default value: false
  device_id         String # default value: 'name' unless specified
  driver_name       String
  ipv4_address      String
  location          String
  share_name        String
  shared            true, false # default value: false
  action            Symbol # defaults to :create if not specified
end

where:

  • windows_printer is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • comment, default, device_id, driver_name, ipv4_address, location, share_name, and shared are the properties available to this resource.

Actions


The windows_printer resource has the following actions:

:create
Default. Create a new printer and printer port, if one doesn’t already exist.
:delete
Delete an existing printer. Note that this resource does not delete the associated printer port.
:nothing
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 windows_printer resource has the following properties:

comment
Ruby Type: String

Optional descriptor for the printer queue.

default
Ruby Type: true, false | Default Value: false

Determines whether or not this should be the system’s default printer.

device_id
Ruby Type: String | Default Value: The resource block's name

An optional property to set the printer queue name if it differs from the resource block’s name. Example: HP LJ 5200 in fifth floor copy room.

driver_name
Ruby Type: String | REQUIRED

The exact name of printer driver installed on the system.

ipv4_address
Ruby Type: String

The IPv4 address of the printer, such as 10.4.64.23

location
Ruby Type: String

Printer location, such as Fifth floor copy room.

share_name
Ruby Type: String

The name used to identify the shared printer.

shared
Ruby Type: true, false | Default Value: false

Determines whether or not the printer is shared.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_printer resource in recipes:

Create a printer:

windows_printer 'HP LaserJet 5th Floor' do
  driver_name 'HP LaserJet 4100 Series PCL6'
  ipv4_address '10.4.64.38'
end

Delete a printer:

Note: this doesn’t delete the associated printer port. See windows_printer_port above for how to delete the port.

windows_printer 'HP LaserJet 5th Floor' do
  action :delete
end

windows_printer_port resource

windows_printer_port resource page

Use the windows_printer_port resource to create and delete TCP/IPv4 printer ports on Windows.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_printer_port resource is:

windows_printer_port 'name' do
  ipv4_address          String # default value: 'name' unless specified
  port_description      String
  port_name             String
  port_number           Integer # default value: 9100
  port_protocol         Integer # default value: 1
  snmp_enabled          true, false # default value: false
  action                Symbol # defaults to :create if not specified
end

where:

  • windows_printer_port is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • ipv4_address, port_description, port_name, port_number, port_protocol, and snmp_enabled are the properties available to this resource.

Actions


The windows_printer_port resource has the following actions:

:create
Default. Create the printer port, if one doesn’t already exist.
:delete
Delete an existing printer port.
:nothing
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 windows_printer_port resource has the following properties:

ipv4_address
Ruby Type: String | Default Value: The resource block's name

An optional property for the IPv4 address of the printer if it differs from the resource block’s name.

port_description
Ruby Type: String

The description of the port.

port_name
Ruby Type: String

The port name.

port_number
Ruby Type: Integer | Default Value: 9100

The port number.

port_protocol
Ruby Type: Integer | Default Value: 1
Allowed Values: 1, 2

The printer port protocol: 1 (RAW) or 2 (LPR).

snmp_enabled
Ruby Type: true, false | Default Value: false

Determines if SNMP is enabled on the port.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_printer_port resource in recipes:

Delete a printer port

windows_printer_port '10.4.64.37' do
  action :delete
end

Delete a port with a custom port_name

windows_printer_port '10.4.64.38' do
  port_name 'My awesome port'
  action :delete
end

Create a port with more options

windows_printer_port '10.4.64.39' do
  port_name 'My awesome port'
  snmp_enabled true
  port_protocol 2
end

windows_security_policy resource

windows_security_policy resource page

Use the windows_security_policy resource to set a security policy on the Microsoft Windows platform.

New in Chef Infra Client 16.0.

Syntax


The full syntax for all of the properties that are available to the windows_security_policy resource is:

windows_security_policy 'name' do
  secoption      String # default value: 'name' unless specified
  secvalue       String
  action         Symbol # defaults to :set if not specified
end

where:

  • windows_security_policy 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.
  • secoption and secvalue are the properties available to this resource.

Actions


The windows_security_policy 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
Set the Windows security policy

Properties


The windows_security_policy resource has the following properties:

secoption
Ruby Type: String | Default Value: The resource block's name | REQUIRED
Allowed Values: "ClearTextPassword", "EnableAdminAccount", "EnableGuestAccount", "ForceLogoffWhenHourExpire", "LSAAnonymousNameLookup", "LockoutBadCount", "LockoutDuration", "MaximumPasswordAge", "MinimumPasswordAge", "MinimumPasswordLength", "NewAdministratorName", "NewGuestName", "PasswordComplexity", "PasswordHistorySize", "RequireLogonToChangePassword", "ResetLockoutCount"

The name of the policy to be set on windows platform to maintain its security.

secvalue
Ruby Type: String | REQUIRED

Policy value to be set for policy name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_security_policy resource in recipes:

Set Administrator Account to Enabled:

windows_security_policy 'EnableAdminAccount' do
  secvalue       '1'
  action         :set
end

Rename Administrator Account:

windows_security_policy 'NewAdministratorName' do
  secvalue       'AwesomeChefGuy'
  action         :set
end

Set Guest Account to Disabled:

windows_security_policy 'EnableGuestAccount' do
  secvalue       '0'
  action         :set
end

windows_service resource

windows_service resource page

Use the windows_service resource to create, delete, or manage a service on the Microsoft Windows platform.

Syntax


A windows_service resource block manages the state of a service on a machine that is running Microsoft Windows. For example:

windows_service 'BITS' do
  action :configure_startup
  startup_type :manual
end

The full syntax for all of the properties that are available to the windows_service resource is:

windows_service 'name' do
  binary_path_name      String
  delayed_start         true, false # default value: false
  dependencies          String, Array
  description           String
  desired_access        Integer # default value: 983551
  display_name          String
  error_control         Integer # default value: 1
  init_command          String
  load_order_group      String
  pattern               String
  reload_command        String, false
  restart_command       String, false
  run_as_password       String
  run_as_user           String # default value: "LocalSystem"
  service_name          String # default value: 'name' unless specified
  service_type          Integer # default value: "SERVICE_WIN32_OWN_PROCESS"
  start_command         String, false
  startup_type          Symbol # default value: :automatic
  status_command        String, false
  stop_command          String, false
  supports              Hash # default value: {"restart"=>nil, "reload"=>nil, "status"=>nil}
  timeout               Integer
  action                Symbol # defaults to :nothing if not specified
end

where:

  • windows_service is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • binary_path_name, display_name, desired_access, delayed_start, dependencies, description, error_control, init_command, load_order_group, pattern, reload_command, restart_command, run_as_password, run_as_user, service_name, service_type, start_command, startup_type, status_command, stop_command, supports, and timeout are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

Actions


The windows_service resource has the following actions:

:configure
Configure a pre-existing service. New in Chef Client 14.0.
:configure_startup
Configure a service based on the value of the startup_type property.
:create
Create the service based on the value of the binary_path_name, service_name and/or display_name property. New in Chef Client 14.0.
:delete
Delete the service based on the value of the service_name property. New in Chef Client 14.0.
:disable
Disable a service. This action is equivalent to a Disabled startup type on the Microsoft Windows platform.
:enable
Enable a service at boot. This action is equivalent to an Automatic startup type on the Microsoft Windows platform.
:nothing
Default. Do nothing with a service.
:reload
Reload the configuration for this service. This action is not supported on the Windows platform and will raise an error if used.
:restart
Restart a service.
:start
Start a service, and keep it running until stopped or disabled.
:stop
Stop a service.

Properties


The windows_service resource has the following properties:

binary_path_name
Ruby Type: String

The fully qualified path to the service binary file. The path can also include arguments for an auto-start service. This is required for :create and :configure actions

New in Chef Client 14.0

delayed_start
Ruby Type: true, false | Default Value: false

Set the startup type to delayed start. This only applies if startup_type is :automatic

New in Chef Client 14.0

dependencies
Ruby Type: String, Array

A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify nil or an empty string if the service has no dependencies. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group.

New in Chef Client 14.0

description
Ruby Type: String

Description of the service.

New in Chef Client 14.0

desired_access
Ruby Type: Integer | Default Value: 983551

New in Chef Client 14.0

display_name
Ruby Type: String

The display name to be used by user interface programs to identify the service. This string has a maximum length of 256 characters.

New in Chef Client 14.0

error_control
Ruby Type: Integer | Default Value: 1

New in Chef Client 14.0

load_order_group
Ruby Type: String

The name of the service’s load ordering group(s).

New in Chef Client 14.0

pattern
Ruby Type: String | Default Value: The value provided to 'service_name' or the resource block's name

The pattern to look for in the process table.

reload_command
Ruby Type: String, false

The command used to tell a service to reload its configuration.

restart_command
Ruby Type: String, false

The command used to restart a service.

run_as_password
Ruby Type: String

The password for the user specified by run_as_user.

run_as_user
Ruby Type: String | Default Value: localsystem

The user under which a Microsoft Windows service runs.

service_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the service name if it differs from the resource block’s name.

service_type
Ruby Type: Integer | Default Value: 16

New in Chef Client 14.0

start_command
Ruby Type: String, false

The command used to start a service.

startup_type
Ruby Type: Symbol | Default Value: :automatic
Allowed Values: :automatic, :disabled, :manual

Use to specify the startup type of the service.

status_command
Ruby Type: String, false

The command used to check the run status for a service.

stop_command
Ruby Type: String, false

The command used to stop a service.

supports
Ruby Type: Hash | Default Value: {"restart"=>nil, "reload"=>nil, "status"=>nil}

A list of properties that controls how Chef Infra Client is to attempt to manage a service: :restart, :reload, :status. For :restart, the init script or other service provider can use a restart command; if :restart is not specified, Chef Infra Client attempts to stop and then start a service. For :reload, the init script or other service provider can use a reload command. For :status, the init script or other service provider can use a status command to determine if the service is running; if :status is not specified, Chef Infra Client attempts to match the service_name against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: { restart: false, reload: false, status: false } for all platforms (except for the Red Hat platform family, which defaults to { restart: false, reload: false, status: true }.)

timeout
Ruby Type: Integer | Default Value: 60

The amount of time (in seconds) to wait before timing out.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_service resource in recipes:

Start a service manually

windows_service 'BITS' do
  action :configure_startup
  startup_type :manual
end

Create a service

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
end

Create service with ‘service_name’ and ‘display_name’:

windows_service 'Create chef client as service' do
  action :create
  display_name "CHEF-CLIENT"
  service_name "chef-client"
  binary_path_name "C:\\opscode\\chef\\bin"
end

Create service with the :manual startup type:

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :manual
end

Create a service with the :disabled startup type:

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :disabled
end

Create service with the :automatic startup type and delayed start enabled:

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :automatic
  delayed_start true
end

Create service with a description:

windows_service 'chef-client' do
  action :create
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :automatic
  description "Chef client as service"
end

Delete a service

Delete service with the 'name' of chef-client:

windows_service 'chef-client' do
  action :delete
end

Delete service with 'service_name':

windows_service 'Delete chef client' do
  action :delete
  service_name "chef-client"
end

Configure a service

Change an existing service from automatic to manual startup:

windows_service 'chef-client' do
  action :configure
  binary_path_name "C:\\opscode\\chef\\bin"
  startup_type :manual
end

windows_share resource

windows_share resource page

Use the windows_share resource to create, modify and remove Windows shares.

New in Chef Infra Client 14.7.

Syntax


The full syntax for all of the properties that are available to the windows_share resource is:

windows_share 'name' do
  ca_timeout                  Integer # default value: 0
  change_users                Array
  concurrent_user_limit       Integer # default value: 0
  continuously_available      true, false # default value: false
  description                 String
  encrypt_data                true, false # default value: false
  full_users                  Array
  path                        String
  read_users                  Array
  scope_name                  String # default value: "*"
  share_name                  String # default value: 'name' unless specified
  temporary                   true, false # default value: false
  action                      Symbol # defaults to :create if not specified
end

where:

  • windows_share 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.
  • ca_timeout, change_users, concurrent_user_limit, continuously_available, description, encrypt_data, full_users, path, read_users, scope_name, share_name, and temporary are the properties available to this resource.

Actions


The windows_share resource has the following actions:

:create
Create and modify Windows shares.
:delete
Delete an existing Windows share.
: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 windows_share resource has the following properties:

ca_timeout
Ruby Type: Integer | Default Value: 0

The continuous availability time-out for the share.

change_users
Ruby Type: Array

The users that should have ‘modify’ permission on the share in domain\username format.

concurrent_user_limit
Ruby Type: Integer | Default Value: 0

The maximum number of concurrently connected users the share can accommodate.

continuously_available
Ruby Type: true, false | Default Value: false

Indicates that the share is continuously available.

description
Ruby Type: String

The description to be applied to the share.

encrypt_data
Ruby Type: true, false | Default Value: false

Indicates that the share is encrypted.

full_users
Ruby Type: Array

The users that should have ‘Full control’ permissions on the share in domain\username format.

path
Ruby Type: String

The path of the folder to share. Required when creating. If the share already exists on a different path then it is deleted and re-created.

read_users
Ruby Type: Array

The users that should have ‘read’ permission on the share in domain\username format.

scope_name
Ruby Type: String | Default Value: *

The scope name of the share.

share_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the share name if it differs from the resource block’s name.

temporary
Ruby Type: true, false | Default Value: false

The lifetime of the new SMB share. A temporary share does not persist beyond the next restart of the computer.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_share resource in recipes:

Create a share:

windows_share 'foo' do
  action :create
  path 'C:\foo'
  full_users ['DOMAIN_A\some_user', 'DOMAIN_B\some_other_user']
  read_users ['DOMAIN_C\Domain users']
end

Delete a share:

windows_share 'foo' do
  action :delete
end

windows_shortcut resource

windows_shortcut resource page

Use the windows_shortcut resource to create shortcut files on Windows.

New in Chef Infra Client 14.0.

Syntax


The full syntax for all of the properties that are available to the windows_shortcut resource is:

windows_shortcut 'name' do
  arguments          String
  cwd                String
  description        String
  iconlocation       String
  shortcut_name      String # default value: 'name' unless specified
  target             String
  action             Symbol # defaults to :create if not specified
end

where:

  • windows_shortcut is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • arguments, cwd, description, iconlocation, shortcut_name, and target are the properties available to this resource.

Actions


The windows_shortcut resource has the following actions:

:create
Default. Create or modify a Windows shortcut.
:nothing
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 windows_shortcut resource has the following properties:

arguments
Ruby Type: String

Arguments to pass to the target when the shortcut is executed.

cwd
Ruby Type: String

Working directory to use when the target is executed.

description
Ruby Type: String

The description of the shortcut

iconlocation
Ruby Type: String

Icon to use for the shortcut. Accepts the format of path, index, where index is the icon file to use. See Microsoft’s documentation for details

shortcut_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the shortcut name if it differs from the resource block’s name.

target
Ruby Type: String

The destination that the shortcut links to.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_shortcut resource in recipes:

Create a shortcut with a description:

windows_shortcut 'C:\shortcut_dir.lnk' do
  target 'C:\original_dir'
  description 'Make a shortcut to C:\original_dir'
end

windows_task resource

windows_task resource page

Use the windows_task resource to create, delete or run a Windows scheduled task.

Note

The windows_task resource that was provided as part of the windows cookbook included the :change action, which has been removed from windows_task in Chef client. The :create action can be used instead to update an existing task.

New in Chef Infra Client 13.0.

Syntax


The full syntax for all of the properties that are available to the windows_task resource is:

windows_task 'name' do
  command                             String
  cwd                                 String
  day                                 String, Integer
  description                         String
  disallow_start_if_on_batteries      true, false # default value: false
  execution_time_limit                String, Integer # default value: "PT72H (72 hours in ISO8601 duration format)"
  force                               true, false # default value: false
  frequency                           Symbol
  frequency_modifier                  Integer, String # default value: 1
  idle_time                           Integer
  interactive_enabled                 true, false # default value: false
  minutes_duration                    String, Integer
  minutes_interval                    String, Integer
  months                              String
  password                            String
  priority                            Integer # default value: 7
  random_delay                        String, Integer
  run_level                           Symbol # default value: :limited
  start_day                           String # default value: The current date.
  start_time                          String
  start_when_available                true, false # default value: false
  stop_if_going_on_batteries          true, false # default value: false
  task_name                           String # default value: 'name' unless specified
  user                                String # default value: The localized SYSTEM user for the node.
  action                              Symbol # defaults to :create if not specified
end

where:

  • windows_task is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • command, cwd, day, description, disallow_start_if_on_batteries, execution_time_limit, force, frequency, frequency_modifier, idle_time, interactive_enabled, minutes_duration, minutes_interval, months, password, priority, random_delay, run_level, start_day, start_time, start_when_available, stop_if_going_on_batteries, task_name, and user are the properties available to this resource.

Actions


The windows_task resource has the following actions:

:create
Creates a task, or updates an existing task if any property has changed.
:delete
Deletes a task.
:disable
Disables a task.
:enable
Enables a task.
:end
Ends a task.
: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
Runs a task.

Properties


The windows_task resource has the following properties:

command
Ruby Type: String

The command to be executed by the windows scheduled task.

cwd
Ruby Type: String

The directory the task will be run from.

day
Ruby Type: String, Integer

The day(s) on which the task runs.

  • Use with frequency :monthly and :weekly tasks,
  • Valid values with frequency :weekly are MON-SUN or \*.
  • Valid values with frequency :monthly are 1-31 or MON to SUN and LASTDAY.
    • Use MON-SUN or LASTDAY if you are setting frequency_modifier as "FIRST, SECOND, THIRD etc." else use 1-31.
    • Multiple days should be comma separated. e.g "1, 2, 3" or "MON, WEN, FRI".

description
Ruby Type: String

The task description.

New in Chef Client 14.7

disallow_start_if_on_batteries
Ruby Type: true, false | Default Value: false

Disallow start of the task if the system is running on battery power.

New in Chef Client 14.4

execution_time_limit
Ruby Type: String, Integer | Default Value: PT72H (72 hours in ISO8601 duration format)

The maximum time the task will run. This field accepts either seconds or an ISO8601 duration value.

force
Ruby Type: true, false | Default Value: false

When used with create, will update the task.

frequency
Ruby Type: Symbol
Allowed Values: :daily, :hourly, :minute, :monthly, :none, :on_idle, :on_logon, :once, :onstart, :weekly

  • Frequency with which to run the task.
  • This is a mandatory property in Chef 14.1
  • Valid values: :minute, :hourly, :daily, :weekly, :monthly, :none, :once, :on_logon, :onstart, :on_idle.
  • The :once value requires the start_time property.

frequency_modifier
Ruby Type: Integer, String | Default Value: 1

  • For frequency :minute valid values are 1 to 1439

  • For frequency :hourly valid values are 1 to 23

  • For frequency :daily valid values are 1 to 365

  • For frequency :weekly valid values are 1 to 52

  • For frequency :monthly valid values are ('FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST') OR 1-12.

    : - e.g. If user want to run the task on second week of the month use frequency_modifier value as SECOND. Multiple values for weeks of the month should be comma separated e.g. "FIRST, THIRD, LAST". - To run task every (n) months user values ‘1-12’.

idle_time
Ruby Type: Integer

For :on_idle frequency, the time (in minutes) without user activity that must pass to trigger the task, from 1 - 999.

interactive_enabled
Ruby Type: true, false | Default Value: false

Allow task to run interactively or non-interactively. Requires user and password to also be set.

minutes_duration
Ruby Type: String, Integer

minutes_interval
Ruby Type: String, Integer

months
Ruby Type: String

The Months of the year on which the task runs, such as: JAN, FEB or *. Multiple months should be comma delimited. e.g. Jan, Feb, Mar, Dec.

password
Ruby Type: String

The user’s password. The user property must be set if using this property.

priority
Ruby Type: Integer | Default Value: 7

Use to set Priority Levels range from 0 to 10.

random_delay
Ruby Type: String, Integer

Delays the task up to a given time (in seconds).

run_level
Ruby Type: Symbol | Default Value: :limited
Allowed Values: :highest, :limited

Run with :limited or :highest privileges.

start_day
Ruby Type: String | Default Value: The current date.

Specifies the first date on which the task runs in MM/DD/YYYY format.

start_time
Ruby Type: String

Specifies the start time to run the task, in HH:mm format.

start_when_available
Ruby Type: true, false | Default Value: false

To start the task at any time after its scheduled time has passed.

New in Chef Client 14.15

stop_if_going_on_batteries
Ruby Type: true, false | Default Value: false

Scheduled task option when system is switching on battery.

New in Chef Client 14.4

task_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the task name if it differs from the resource block’s name. Example: Task Name or /Task Name

user
Ruby Type: String | Default Value: The localized SYSTEM user for the node.

The user to run the task as.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_task resource in recipes:

Create a scheduled task to run every 15 minutes as the Administrator user:

windows_task 'chef-client' do
  user 'Administrator'
  password 'password'
  command 'chef-client'
  run_level :highest
  frequency :minute
  frequency_modifier 15
end

Create a scheduled task to run every 2 days:

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :daily
  frequency_modifier 2
end

Create a scheduled task to run on specific days of the week:

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :weekly
  day 'Mon, Thu'
end

Create a scheduled task to run only once:

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :once
  start_time "16:10"
end

Create a scheduled task to run on current day every 3 weeks and delay upto 1 min:

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :weekly
  frequency_modifier 3
  random_delay '60'
end

Create a scheduled task to run weekly starting on Dec 28th 2018:

windows_task 'chef-client 8' do
  command 'chef-client'
  run_level :highest
  frequency :weekly
  start_day '12/28/2018'
end

Create a scheduled task to run every Monday, Friday every 2 weeks:

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :weekly
  frequency_modifier 2
  day 'Mon, Fri'
end

Create a scheduled task to run when computer is idle with idle duration 20 min:

windows_task 'chef-client' do
  command 'chef-client'
  run_level :highest
  frequency :on_idle
  idle_time 20
end

Delete a task named “old task”:

windows_task 'old task' do
  action :delete
end

Enable a task named “chef-client”:

windows_task 'chef-client' do
  action :enable
end

Disable a task named “ProgramDataUpdater” with TaskPath “\Microsoft\Windows\Application Experience\ProgramDataUpdater”

windows_task '\Microsoft\Windows\Application Experience\ProgramDataUpdater' do
  action :disable
end

windows_uac resource

windows_uac resource page

The windows_uac resource configures UAC on Windows hosts by setting registry keys at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

New in Chef Infra Client 15.0.

Syntax


The full syntax for all of the properties that are available to the windows_uac resource is:

windows_uac 'name' do
  consent_behavior_admins       Symbol # default value: :prompt_for_consent_non_windows_binaries
  consent_behavior_users        Symbol # default value: :prompt_for_creds
  detect_installers             true, false
  enable_uac                    true, false # default value: true
  prompt_on_secure_desktop      true, false # default value: true
  require_signed_binaries       true, false # default value: false
  action                        Symbol # defaults to :configure if not specified
end

where:

  • windows_uac 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.
  • consent_behavior_admins, consent_behavior_users, detect_installers, enable_uac, prompt_on_secure_desktop, and require_signed_binaries are the properties available to this resource.

Actions


The windows_uac resource has the following actions:

:configure
Configures UAC by setting registry keys at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.
: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 windows_uac resource has the following properties:

consent_behavior_admins
Ruby Type: Symbol | Default Value: :prompt_for_consent_non_windows_binaries
Allowed Values: :no_prompt, :prompt_for_consent, :prompt_for_consent_non_windows_binaries, :prompt_for_creds, :secure_prompt_for_consent, :secure_prompt_for_creds

Behavior of the elevation prompt for administrators in Admin Approval Mode. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorAdmin.

consent_behavior_users
Ruby Type: Symbol | Default Value: :prompt_for_creds
Allowed Values: :auto_deny, :prompt_for_creds, :secure_prompt_for_creds

Behavior of the elevation prompt for standard users. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ConsentPromptBehaviorUser.

detect_installers
Ruby Type: true, false

Detect application installations and prompt for elevation. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\EnableInstallerDetection.

enable_uac
Ruby Type: true, false | Default Value: true

Enable or disable UAC Admin Approval Mode. If this is changed a system restart is required. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA.

prompt_on_secure_desktop
Ruby Type: true, false | Default Value: true

Switch to the secure desktop when prompting for elevation. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\PromptOnSecureDesktop.

require_signed_binaries
Ruby Type: true, false | Default Value: false

Only elevate executables that are signed and validated. Sets HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA\ValidateAdminCodeSignatures.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_uac resource in recipes:

Disable UAC prompts for the admin:

windows_uac 'Disable UAC prompts for the admin' do
  enable_uac true
  prompt_on_secure_desktop false
  consent_behavior_admins :no_prompt
end

Disable UAC entirely:

windows_uac 'Disable UAC entirely' do
  enable_uac false
end

windows_user_privilege resource

windows_user_privilege resource page

The windows_user_privilege resource allows to add and set principal (User/Group) to the specified privilege. Ref: https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/user-rights-assignment

New in Chef Infra Client 16.0.

Syntax


The full syntax for all of the properties that are available to the windows_user_privilege resource is:

windows_user_privilege 'name' do
  principal      String # default value: 'name' unless specified
  privilege      Array, String
  users          Array
  action         Symbol # defaults to :add if not specified
end

where:

  • windows_user_privilege 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.
  • principal, privilege, and users are the properties available to this resource.

Actions


The windows_user_privilege resource has the following actions:

:add
Add a user privilege
:clear
Clear all user privileges
: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 user privilege
:set
Set the privileges that are listed in the privilege property for only the users listed in the users property.

Properties


The windows_user_privilege resource has the following properties:

principal
Ruby Type: String | Default Value: The resource block's name

An optional property to add the user to the given privilege. Use only with add and remove action.

privilege
Ruby Type: Array, String | REQUIRED

Privilege to set for users.

users
Ruby Type: Array

An optional property to set the privilege for given users. Use only with set action.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_user_privilege resource in recipes:

Set the SeNetworkLogonRight Privilege for the Builtin Administrators Group and Authenticated Users:

windows_user_privilege 'Network Logon Rights' do
  privilege      'SeNetworkLogonRight'
  users          ['BUILTIN\Administrators', 'NT AUTHORITY\Authenticated Users']
  action         :set
end

Add the SeDenyRemoteInteractiveLogonRight Privilege to the Builtin Guests and Local Accounts User Groups:

windows_user_privilege 'Remote interactive logon' do
  privilege      'SeDenyRemoteInteractiveLogonRight'
  users          ['Builtin\Guests', 'NT AUTHORITY\Local Account']
  action         :add
end

Provide only the Builtin Guests and Administrator Groups with the SeCreatePageFile Privilege:

windows_user_privilege 'Create Pagefile' do
  privilege      'SeCreatePagefilePrivilege'
  users          ['BUILTIN\Guests', 'BUILTIN\Administrators']
  action         :set
end

Remove the SeCreatePageFile Privilege from the Builtin Guests Group:

windows_user_privilege 'Create Pagefile' do
  privilege      'SeCreatePagefilePrivilege'
  users          ['BUILTIN\Guests']
  action         :remove
end

Clear all users from the SeDenyNetworkLogonRight Privilege:

windows_user_privilege 'Allow any user the Network Logon right' do
  privilege      'SeDenyNetworkLogonRight'
  action         :clear
end

windows_workgroup resource

windows_workgroup resource page

Use the windows_workgroup resource to join or change the workgroup of a Windows host.

New in Chef Infra Client 14.5.

Syntax


The full syntax for all of the properties that are available to the windows_workgroup resource is:

windows_workgroup 'name' do
  password            String
  reboot              Symbol # default value: :immediate
  sensitive           true, false # default value: true
  user                String
  workgroup_name      String # default value: 'name' unless specified
  action              Symbol # defaults to :join if not specified
end

where:

  • windows_workgroup is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • password, reboot, sensitive, user, and workgroup_name are the properties available to this resource.

Actions


The windows_workgroup resource has the following actions:

:join
Update the workgroup.
:nothing
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 windows_workgroup resource has the following properties:

password
Ruby Type: String

The password for the local administrator user. Required if using the user property.

reboot
Ruby Type: Symbol | Default Value: :immediate
Allowed Values: :never, :reboot_now, :request_reboot

Controls the system reboot behavior post workgroup joining. Reboot immediately, after the Chef Infra Client run completes, or never. Note that a reboot is necessary for changes to take effect.

user
Ruby Type: String

The local administrator user to use to change the workgroup. Required if using the password property.

workgroup_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the workgroup name if it differs from the resource block’s name.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the windows_workgroup resource in recipes:

Join a workgroup:

windows_workgroup 'myworkgroup'

Join a workgroup using a specific user:

windows_workgroup 'myworkgroup' do
  user 'Administrator'
  password 'passw0rd'
end

yum_package resource

yum_package resource page

Use the yum_package resource to install, upgrade, and remove packages with Yum for the Red Hat and CentOS platforms. The yum_package resource is able to resolve provides data for packages much like Yum can do when it is run from the command line. This allows a variety of options for installing packages, like minimum versions, virtual provides, and library names.

Note

Support for using file names to install packages (as in yum_package "/bin/sh") is not available because the volume of data required to parse for this is excessive.

Syntax


The full syntax for all of the properties that are available to the yum_package resource is:

yum_package 'name' do
  allow_downgrade      true, false # default value: true
  arch                 String, Array
  flush_cache          Hash # default value: {"before"=>false, "after"=>false}
  options              String, Array
  package_name         String, Array
  source               String
  timeout              String, Integer
  version              String, Array
  yum_binary           String
  action               Symbol # defaults to :install if not specified
end

where:

  • yum_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • allow_downgrade, arch, flush_cache, options, package_name, source, timeout, version, and yum_binary are the properties available to this resource.

Actions


The yum_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:lock
Locks the yum package to a specific version.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:remove
Remove a package.
:unlock
Unlocks the yum package so that it can be upgraded to a newer version.
:upgrade
Install a package and/or ensure that a package is the latest version. This action will ignore the version attribute.

Properties


The yum_package resource has the following properties:

allow_downgrade
Ruby Type: true, false | Default Value: true

Allow downgrading a package to satisfy requested version requirements.

arch
Ruby Type: String, Array

The architecture of the package to be installed or upgraded. This value can also be passed as part of the package name.

flush_cache
Ruby Type: Hash | Default Value: {"before"=>false, "after"=>false}

Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Accepts a Hash in the form: { :before => true/false, :after => true/false } or an Array in the form [ :before, :after ].

Yum automatically synchronizes remote metadata to a local cache. Chef Infra Client creates a copy of the local cache, and then stores it in-memory during a Chef Infra Client run. The in-memory cache allows packages to be installed during a Chef Infra Client run without the need to continue synchronizing the remote metadata to the local cache while the Chef Infra Client run is in-progress.

As an array:

yum_package 'some-package' do
  #...
  flush_cache [ :before ]
  #...
end

and as a Hash:

yum_package 'some-package' do
  #...
  flush_cache( { :after => true } )
  #...
end

Note

The flush_cache property does not flush the local Yum cache! Use Yum tools—yum clean headers, yum clean packages, yum clean all—to clean the local Yum cache.

options
Ruby Type: String, Array

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

One of the following: the name of a package, the name of a package and its architecture, the name of a dependency. Default value: the name of the resource block. See “Syntax” section above for more information.

source
Ruby Type: String

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded. This property is ignored when using the :upgrade action.

yum_binary
Ruby Type: String

The path to the yum binary.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to:

  • Download the specified packages and versions via a single HTTP transaction
  • Update or install multiple packages with a single resource during a Chef Infra Client run

For example, installing multiple packages:

package %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(package1 package2)  do
  action :nothing
end

log 'call a notification' do
  notifies :install, 'package[package1, package2]', :immediately
end

Note

Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the package_name or version properties.

Examples


The following examples demonstrate various approaches for using the yum_package resource in recipes:

Install an exact version:

yum_package 'netpbm = 10.35.58-8.el8'

Install a minimum version:

yum_package 'netpbm >= 10.35.58-8.el8'

Install a minimum version using the default action:

yum_package 'netpbm'

Install a version without worrying about the exact release:

yum_package 'netpbm-10.35*'

To install a package:

yum_package 'netpbm' do
  action :install
end

To install a partial minimum version:

yum_package 'netpbm >= 10'

To install a specific architecture:

yum_package 'netpbm' do
  arch 'i386'
end

or:

yum_package 'netpbm.x86_64'

To install a specific version-release

yum_package 'netpbm' do
  version '10.35.58-8.el8'
end

Handle cookbook_file and yum_package resources in the same recipe:

When a cookbook_file resource and a yum_package resource are both called from within the same recipe, use the flush_cache attribute to dump the in-memory Yum cache, and then use the repository immediately to ensure that the correct package is installed:

cookbook_file '/etc/yum.repos.d/custom.repo' do
  source 'custom'
  mode '0755'
end

yum_package 'pkg-that-is-only-in-custom-repo' do
  action :install
  flush_cache [ :before ]
end

yum_repository resource

yum_repository resource page

Use the yum_repository resource to manage a Yum repository configuration file located at /etc/yum.repos.d/repositoryid.repo on the local machine. This configuration file specifies which repositories to reference, how to handle cached data, etc.

New in Chef Infra Client 12.14.

Syntax


The full syntax for all of the properties that are available to the yum_repository resource is:

yum_repository 'name' do
  baseurl                    String, Array
  clean_metadata             true, false # default value: true
  cost                       String
  description                String # default value: "Yum Repository"
  enabled                    true, false # default value: true
  enablegroups               true, false
  exclude                    String
  failovermethod             String
  fastestmirror_enabled      true, false
  gpgcheck                   true, false # default value: true
  gpgkey                     String, Array
  http_caching               String
  include_config             String
  includepkgs                String
  keepalive                  true, false
  make_cache                 true, false # default value: true
  max_retries                String, Integer
  metadata_expire            String
  metalink                   String
  mirror_expire              String
  mirrorlist                 String
  mirrorlist_expire          String
  mode                       String, Integer # default value: "0644"
  options                    Hash
  password                   String
  priority                   String
  proxy                      String
  proxy_password             String
  proxy_username             String
  repo_gpgcheck              true, false
  report_instanceid          true, false
  repositoryid               String # default value: 'name' unless specified
  skip_if_unavailable        true, false
  source                     String
  sslcacert                  String
  sslclientcert              String
  sslclientkey               String
  sslverify                  true, false
  throttle                   String, Integer
  timeout                    String
  username                   String
  action                     Symbol # defaults to :create if not specified
end

where:

  • yum_repository is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • baseurl, clean_metadata, cost, description, enabled, enablegroups, exclude, failovermethod, fastestmirror_enabled, gpgcheck, gpgkey, http_caching, include_config, includepkgs, keepalive, make_cache, max_retries, metadata_expire, metalink, mirror_expire, mirrorlist, mirrorlist_expire, mode, options, password, priority, proxy, proxy_password, proxy_username, repo_gpgcheck, report_instanceid, repositoryid, skip_if_unavailable, source, sslcacert, sslclientcert, sslclientkey, sslverify, throttle, timeout, and username are the properties available to this resource.

Actions


The yum_repository resource has the following actions:

:create
Create a repository based on the properties.
:makecache
Force the creation of the repository cache. This is also done automatically when a repository is updated.
: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 repository.

Properties


The yum_repository resource has the following properties:

baseurl
Ruby Type: String, Array

URL to the directory where the Yum repository’s repodata directory lives. Can be an http://, https:// or a ftp:// URLs. You can specify multiple URLs in one baseurl statement.

clean_metadata
Ruby Type: true, false | Default Value: true

Specifies whether you want to purge all of the packages downloaded from a Yum repository and held in a cache directory.

cost
Ruby Type: String

Relative cost of accessing this repository. Useful for weighing one repo’s packages as greater/less than any other.

description
Ruby Type: String | Default Value: Yum Repository

Descriptive name for the repository channel and maps to the ‘name’ parameter in a repository .conf.

enabled
Ruby Type: true, false | Default Value: true

Specifies whether or not Yum should use this repository.

enablegroups
Ruby Type: true, false

Specifies whether Yum will allow the use of package groups for this repository.

exclude
Ruby Type: String

List of packages to exclude from updates or installs. This should be a space separated list. Shell globs using wildcards (eg. * and ?) are allowed.

failovermethod
Ruby Type: String
Allowed Values: "priority", "roundrobin"

Method to determine how to switch to a new server if the current one fails, which can either be roundrobin or priority. roundrobin randomly selects a URL out of the list of URLs to start with and proceeds through each of them as it encounters a failure contacting the host. priority starts from the first baseurl listed and reads through them sequentially.

fastestmirror_enabled
Ruby Type: true, false

Specifies whether to use the fastest mirror from a repository configuration when more than one mirror is listed in that configuration.

gpgcheck
Ruby Type: true, false | Default Value: true

Specifies whether or not Yum should perform a GPG signature check on the packages received from a repository.

gpgkey
Ruby Type: String, Array

URL pointing to the ASCII-armored GPG key file for the repository. This is used if Yum needs a public key to verify a package and the required key hasn’t been imported into the RPM database. If this option is set, Yum will automatically import the key from the specified URL. Multiple URLs may be specified in the same manner as the baseurl option. If a GPG key is required to install a package from a repository, all keys specified for that repository will be installed. Multiple URLs may be specified in the same manner as the baseurl option. If a GPG key is required to install a package from a repository, all keys specified for that repository will be installed.

http_caching
Ruby Type: String
Allowed Values: "all", "none", "packages"

Determines how upstream HTTP caches are instructed to handle any HTTP downloads that Yum does. This option can take the following values:

  • all means all HTTP downloads should be cached
  • packages means only RPM package downloads should be cached, but not repository metadata downloads
  • none means no HTTP downloads should be cached.

The default value of all is recommended unless you are experiencing caching related issues.

include_config
Ruby Type: String

An external configuration file using the format url://to/some/location.

includepkgs
Ruby Type: String

Inverse of exclude property. This is a list of packages you want to use from a repository. If this option lists only one package then that is all Yum will ever see from the repository.

keepalive
Ruby Type: true, false

Determines whether or not HTTP/1.1 keep-alive should be used with this repository.

make_cache
Ruby Type: true, false | Default Value: true

Determines whether package files downloaded by Yum stay in cache directories. By using cached data, you can carry out certain operations without a network connection.

max_retries
Ruby Type: String, Integer

Number of times any attempt to retrieve a file should retry before returning an error. Setting this to 0 makes Yum try forever.

metadata_expire
Ruby Type: String

Time (in seconds) after which the metadata will expire. If the current metadata downloaded is less than the value specified, then Yum will not update the metadata against the repository. If you find that Yum is not downloading information on updates as often as you would like lower the value of this option. You can also change from the default of using seconds to using days, hours or minutes by appending a d, h or m respectively. The default is six hours to compliment yum-updates running once per hour. It is also possible to use the word never, meaning that the metadata will never expire. Note: When using a metalink file, the metalink must always be newer than the metadata for the repository due to the validation, so this timeout also applies to the metalink file.

Note

When using a metalink file, the metalink must always be newer than the metadata for the repository due to the validation, so this timeout also applies to the metalink file.

metalink
Ruby Type: String

Specifies a URL to a metalink file for the repomd.xml, a list of mirrors for the entire repository are generated by converting the mirrors for the repomd.xml file to a baseurl.

mirror_expire
Ruby Type: String

Time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than this many seconds old then Yum will not download another copy of the mirrorlist, it has the same extra format as metadata_expire. If you find that Yum is not downloading the mirrorlists as often as you would like lower the value of this option. You can also change from the default of using seconds to using days, hours or minutes by appending a d, h or m respectively.

mirrorlist
Ruby Type: String

URL to a file containing a list of baseurls. This can be used instead of or with the baseurl option. Substitution variables, described below, can be used with this option.

mirrorlist_expire
Ruby Type: String

Specifies the time (in seconds) after which the mirrorlist locally cached will expire. If the current mirrorlist is less than the value specified, then Yum will not download another copy of the mirrorlist. You can also change from the default of using seconds to using days, hours or minutes by appending a d, h or m respectively.

mode
Ruby Type: String, Integer | Default Value: "0644"

Permissions mode of .repo file on disk. This is useful for scenarios where secrets are in the repo file. If this value is set to 600, normal users will not be able to use Yum search, Yum info, etc.

options
Ruby Type: Hash

Specifies the repository options.

password
Ruby Type: String

Password to use with the username for basic authentication.

priority
Ruby Type: String

Assigns a priority to a repository where the priority value is between 1 and 99 inclusive. Priorities are used to enforce ordered protection of repositories. Packages from repositories with a lower priority (higher numerical value) will never be used to upgrade packages that were installed from a repository with a higher priority (lower numerical value). The repositories with the lowest numerical priority number have the highest priority.

proxy
Ruby Type: String

URL to the proxy server that Yum should use.

proxy_password
Ruby Type: String

Password for this proxy.

proxy_username
Ruby Type: String

Username to use for proxy.

repo_gpgcheck
Ruby Type: true, false

Determines whether or not Yum should perform a GPG signature check on the repodata from this repository.

report_instanceid
Ruby Type: true, false

Determines whether to report the instance ID when using Amazon Linux AMIs and repositories.

repositoryid
Ruby Type: String | Default Value: The resource block's name

An optional property to set the repository name if it differs from the resource block’s name.

skip_if_unavailable
Ruby Type: true, false

Allow yum to continue if this repository cannot be contacted for any reason.

source
Ruby Type: String

Use a custom template source instead of the default one.

sslcacert
Ruby Type: String

Path to the directory containing the databases of the certificate authorities Yum should use to verify SSL certificates.

sslclientcert
Ruby Type: String

Path to the SSL client certificate Yum should use to connect to repos/remote sites.

sslclientkey
Ruby Type: String

Path to the SSL client key Yum should use to connect to repos/remote sites.

sslverify
Ruby Type: true, false

Determines whether Yum will verify SSL certificates/hosts.

throttle
Ruby Type: String, Integer

Enable bandwidth throttling for downloads.

timeout
Ruby Type: String

Number of seconds to wait for a connection before timing out. Defaults to 30 seconds. This may be too short of a time for extremely overloaded sites.

username
Ruby Type: String

Username to use for basic authentication to a repository.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the yum_repository resource in recipes:

Add an internal company repository:

yum_repository 'OurCo' do
  description 'OurCo yum repository'
  mirrorlist 'http://artifacts.ourco.org/mirrorlist?repo=ourco-8&arch=$basearch'
  gpgkey 'http://artifacts.ourco.org/pub/yum/RPM-GPG-KEY-OURCO-8'
  action :create
end
```ruby

**Delete a repository**:

```ruby
yum_repository 'CentOS-Media' do
  action :delete
end

zypper_package resource

zypper_package resource page

Use the zypper_package resource to install, upgrade, and remove packages with Zypper for the SUSE Enterprise and openSUSE platforms.

Syntax


The full syntax for all of the properties that are available to the zypper_package resource is:

zypper_package 'name' do
  allow_downgrade      true, false # default value: true
  global_options       String, Array
  gpg_check            true, false # default value: "true"
  options              String, Array
  package_name         String, Array
  source               String
  timeout              String, Integer
  version              String, Array
  action               Symbol # defaults to :install if not specified
end

where:

  • zypper_package is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • allow_downgrade, global_options, gpg_check, options, package_name, source, timeout, and version are the properties available to this resource.

Actions


The zypper_package resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:lock
Locks the zypper package to a specific version.
:nothing
This resource block does not act unless notified by another resource to take action. Once notified, this resource block either runs immediately or is queued up to run at the end of a Chef Infra Client run.
:purge
Purge a package. This action typically removes the configuration files as well as the package.
:reconfig
Reconfigure a package. This action requires a response file.
:remove
Remove a package.
:unlock
Unlocks the zypper package so that it can be upgraded to a newer version.
:upgrade
Install a package and/or ensure that a package is the latest version.

Properties


The zypper_package resource has the following properties:

allow_downgrade
Ruby Type: true, false | Default Value: true

Allow downgrading a package to satisfy requested version requirements.

New in Chef Client 13.6

global_options
Ruby Type: String, Array

One (or more) additional command options that are passed to the command. For example, common zypper directives, such as --no-recommends. See the zypper man page for the full list.

New in Chef Client 14.6

gpg_check
Ruby Type: true, false | Default Value: true

Verify the package’s GPG signature. Can also be controlled site-wide using the zypper_check_gpg config option.

options
Ruby Type: String, Array

One (or more) additional command options that are passed to the command.

package_name
Ruby Type: String, Array

An optional property to set the package name if it differs from the resource block’s name.

source
Ruby Type: String

The optional path to a package on the local file system.

timeout
Ruby Type: String, Integer

The amount of time (in seconds) to wait before timing out.

version
Ruby Type: String, Array

The version of a package to be installed or upgraded.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to:

  • Download the specified packages and versions via a single HTTP transaction
  • Update or install multiple packages with a single resource during a Chef Infra Client run

For example, installing multiple packages:

package %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(package1 package2)  do
  action :nothing
end

log 'call a notification' do
  notifies :install, 'package[package1, package2]', :immediately
end

Note

Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the package_name or version properties.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Multiple Packages

A resource may specify multiple packages and/or versions for platforms that use Apt, Chocolatey, DNF, Homebrew, Pacman, or Zypper package managers. Specifying multiple packages and/or versions allows a single transaction to:

  • Download the specified packages and versions via a single HTTP transaction
  • Update or install multiple packages with a single resource during a Chef Infra Client run

For example, installing multiple packages:

package %w(package1 package2)

Installing multiple packages with versions:

package %w(package1 package2) do
  version [ '1.3.4-2', '4.3.6-1']
end

Upgrading multiple packages:

package %w(package1 package2)  do
  action :upgrade
end

Removing multiple packages:

package %w(package1 package2)  do
  action :remove
end

Purging multiple packages:

package %w(package1 package2)  do
  action :purge
end

Notifications, via an implicit name:

package %w(package1 package2)  do
  action :nothing
end

log 'call a notification' do
  notifies :install, 'package[package1, package2]', :immediately
end

Note

Notifications and subscriptions do not need to be updated when packages and versions are added or removed from the package_name or version properties.

Examples


The following examples demonstrate various approaches for using the zypper_package resource in recipes:

Install a package using package manager:

zypper_package 'name of package' do
  action :install
end

Install a package using local file:

zypper_package 'jwhois' do
  action :install
  source '/path/to/jwhois.rpm'
end

Install without using recommend packages as a dependency:

package 'apache2' do
  options '--no-recommends'
  end

zypper_repository resource

zypper_repository resource page

Use the zypper_repository resource to create Zypper package repositories on SUSE Enterprise Linux and openSUSE systems. This resource maintains full compatibility with the zypper_repository resource in the existing zypper cookbook.

New in Chef Infra Client 13.3.

Syntax


The full syntax for all of the properties that are available to the zypper_repository resource is:

zypper_repository 'name' do
  autorefresh            true, false # default value: true
  baseurl                String
  cookbook               String
  description            String
  enabled                true, false # default value: true
  gpgautoimportkeys      true, false # default value: true
  gpgcheck               true, false # default value: true
  gpgkey                 String
  keeppackages           true, false # default value: false
  mirrorlist             String
  mode                   String, Integer # default value: "0644"
  path                   String
  priority               Integer # default value: 99
  refresh_cache          true, false # default value: true
  repo_name              String # default value: 'name' unless specified
  source                 String
  type                   String # default value: "NONE"
  action                 Symbol # defaults to :create if not specified
end

where:

  • zypper_repository is the resource.
  • name is the name given to the resource block.
  • action identifies which steps Chef Infra Client will take to bring the node into the desired state.
  • autorefresh, baseurl, cookbook, description, enabled, gpgautoimportkeys, gpgcheck, gpgkey, keeppackages, mirrorlist, mode, path, priority, refresh_cache, repo_name, source, and type are the properties available to this resource.

Actions


The zypper_repository resource has the following actions:

:add
Default action. Add a new Zypper repository.
: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 a Zypper repository.
:remove
Remove a Zypper repository.

Properties


The zypper_repository resource has the following properties:

autorefresh
Ruby Type: true, false | Default Value: true

Determines whether or not the repository should be refreshed automatically.

baseurl
Ruby Type: String

The base URL for the Zypper repository, such as http://download.opensuse.org.

cookbook
Ruby Type: String

The cookbook to source the repository template file from. Only necessary if you’re not using the built in template.

description
Ruby Type: String

The description of the repository that will be shown by the zypper repos command.

enabled
Ruby Type: true, false | Default Value: true

Determines whether or not the repository should be enabled.

gpgautoimportkeys
Ruby Type: true, false | Default Value: true

Automatically import the specified key when setting up the repository.

gpgcheck
Ruby Type: true, false | Default Value: true

Determines whether or not to perform a GPG signature check on the repository.

gpgkey
Ruby Type: String

The location of the repository key to be imported.

keeppackages
Ruby Type: true, false | Default Value: false

Determines whether or not packages should be saved.

mirrorlist
Ruby Type: String

The URL of the mirror list that will be used.

mode
Ruby Type: String, Integer | Default Value: 0644

The file mode of the repository file.

path
Ruby Type: String

The relative path from the repository’s base URL.

priority
Ruby Type: Integer | Default Value: 99

Determines the priority of the Zypper repository.

refresh_cache
Ruby Type: true, false | Default Value: true

Determines whether or not the package cache should be refreshed.

repo_name
Ruby Type: String | Default Value: The resource block's name

An optional property to set the repository name if it differs from the resource block’s name.

source
Ruby Type: String

The name of the template for the repository file. Only necessary if you’re not using the built in template.

type
Ruby Type: String | Default Value: NONE

Specifies the repository type.


Common Resource Functionality


Chef resources include common properties, notifications, and resource guards.

Common Properties

The following properties are common to every resource:

compile_time

Ruby Type: true, false | Default Value: false

Control the phase during which the resource is run on the node. Set to true to run while the resource collection is being built (the compile phase). Set to false to run while Chef Infra Client is configuring the node (the converge phase).

ignore_failure

Ruby Type: true, false, :quiet | Default Value: false

Continue running a recipe if a resource fails for any reason. :quiet will not display the full stack trace and the recipe will continue to run if a resource fails.

retries

Ruby Type: Integer | Default Value: 0

The number of attempts to catch exceptions and retry the resource.

retry_delay

Ruby Type: Integer | Default Value: 2

The retry delay (in seconds).

sensitive

Ruby Type: true, false | Default Value: false

Ensure that sensitive resource data is not logged by Chef InfraClient.

Notifications

notifies

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer
subscribes

Ruby Type: Symbol, 'Chef::Resource[String]'

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
  mode '0600'
  owner 'root'
end

service 'nginx' do
  subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately
end

In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during a Chef Infra Client run at which a notification is run. The following timers are available:

:before

Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.

:delayed

Default. Specifies that a notification should be queued up, and then executed at the end of a Chef Infra Client run.

:immediate, :immediately

Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

Guards

A guard property can be used to evaluate the state of a node during the execution phase of a Chef Infra Client run. Based on the results of this evaluation, a guard property is then used to tell Chef Infra Client if it should continue executing a resource. A guard property accepts either a string value or a Ruby block value:

  • A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard property is not applied. String guards in a powershell_script run Windows PowerShell commands and may return true in addition to 0.
  • A block is executed as Ruby code that must return either true or false. If the block returns true, the guard property is applied. If the block returns false, the guard property is not applied.

A guard property is useful for ensuring that a resource is idempotent by allowing that resource to test for the desired state as it is being executed, and then if the desired state is present, for Chef Infra Client to do nothing.

Properties

The following properties can be used to define a guard that is evaluated during the execution phase of a Chef Infra Client run:

not_if

Prevent a resource from executing when the condition returns true.

only_if

Allow a resource to execute only if the condition returns true.

Examples


The following examples demonstrate various approaches for using the zypper_repository resource in recipes:

Add the Apache repo on openSUSE Leap 15:

zypper_repository 'apache' do
  baseurl 'http://download.opensuse.org/repositories/Apache'
  path '/openSUSE_Leap_15.0'
    type 'rpm-md'
  priority '100'
end