These topics are about older versions of Chef. and are no longer actively maintained by Opscode or the Chef community. To read the current documentation for Chef, see http://docs.opscode.com.
Skip to end of metadata
Go to start of metadata
 

 

This content has been moved to docs.opscode.com

See the following links:


Overview

Resources are the basic units of work in Chef - discrete chunks of a system's configuration that are declared in Recipes and Definitions, and applied to your nodes.

They are usually a cross platform abstraction of the thing you're configuring on the host.

For example, packages may be installed via apt, yum, or the BSD ports and packages systems, but the package resource abstracts these differences away so you can specify that a package should be installed in a cross-platform way.

 

This page provides documentation of the Resources included in the Chef library.
Each description is broken in to several categories:

 

Category

Description

Actions

The list of actions for this resource

Attributes

The list of attributes for this resource

Providers

The list of providers for this resource, along with any shortcut resource name. (You can use the shortcut resource name instead of specifying the provider attribute - apt_package rather than package with provider Chef::Provider::Package::Apt.)

Examples

The first section, shows examples of using each action.

 

New custom resources can also be created using Chef's Lightweight Resources and Providers (LWRP) DSL. Opscode provides several cookbooks that define custom Lightweight Resources and Providers (LWRP). Opscode LWRP Resources details those customer LWRPs, grouped with the cookbook that provides them.
 
Early Bird Pricing for #ChefConf ends March 10th

Presentations on best practices for using Chef in IT operations, cloud architecture, and application development from over 30 companies, including Facebook, General Electric, Nordstrom, Forrester Research, Riot GamesAncestry.com, Edmunds, Kickstarter, Message Bus, Nordstrom, Riot Games and Splunk.

April 24-26, 2013 San Francisco, California

Register today

 
 

Meta

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

Common Actions

These actions are available in every resource.

Action

Description

Default

nothing

Do nothing - useful if you want to specify a resource, but only notify it of other actions.

Yes - in the absence of another default action, nothing is the default

Examples

Action Nothing

Common Attributes

These attributes can be set on any resource.

Attribute

Description

ignore_failure

If true, we will continue running the recipe if this resource fails for any reason. (defaults to false)

provider

The class name of a provider to use for this resource.

retries

Number of times to catch exceptions and retry the resource (defaults to 0). Requires Chef >= 0.10.4.

retry_delay

Retry delay in seconds (defaults to 2). Requires Chef >= 0.10.4.

supports

A hash of options that hint providers as to the capabilities of this resource.

Examples:

ignore_failure
provider
supports
Provider and Supports

The supports attribute is only utilized by a few providers in Chef. For example User and Service.

Conditional Execution

You can add additional guards around resources to prevent them from being run unless some other condition is met using not_if or only_if. The most common use of these is to make the execute resource idempotent, but they can be used with any resource.

Conditional Execution Attributes

Attribute

Description

not_if

Do not apply this resource if the given string (shell command) or block (ruby code) results in return code 0 or is true.

only_if

Only apply this resource if the given string (shell command) or block (ruby code) results in return code 0 or is true.

not_if and only_if attributes can be passed as strings or blocks.

  • Strings are executed as a shell command. The attribute is true if the command returns 0.
  • Blocks are Ruby code. The attribute is true if the result is true.

The behavior of the resource depends on whether the attribute was true.

  • not_if {true} - indicates the action should never be performed.
  • not_if {false} - indicates the action should always be performed.
  • only_if {true} - indicates the action should always be performed.
  • only_if {false} - indicates the action should never be performed..

Optional arguments are available.

Argument

Description

Example

:user

Sets the user to run the command as

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

:group

Sets the group to run the command as

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

:environment

A Hash of environment variables to set

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

:cwd

Sets the current working directory before running the command

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

:timeout

Sets a timeout for the command

not_if "sleep 10000", :timeout => 10

Examples:

not_if
only_if

Notifications

Attribute

Description

notifies

Notify another resource to take an action if this resource changes state for any reason.

subscribes

Take action on this resource if another resource changes state. Works similarly to notifies, but the direction of the relationship is reversed.

Notifies Syntax

The basic form of a notification is:

For example, if you need to restart the apache service when you modify a template that configures apache, you would write that like this:

By default, notifications are :delayed, that is they are queued up as they are triggered, and then executed at the very end of the Chef run. If you want to run an action immediately, use :immediately:

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

Subscribes Syntax

The basic form of a subscription is:

The notification timing works the same as notifications, so the following code should achieve the same results as the notification example:

Examples

notifies
notifies multiple resources
notifies multiple resources + chained notifications

The sequencing should end up (follow Chef's ordering principle):
execute foo
template baz
execute restart_baz
package bar
execute final

subscribes

Relative Paths

These paths are available in every resource.

Path

Description

#{ENV['HOME']}

This will return the ~ path in Linux and Mac, or the %HOMEPATH% in Windows.

Examples

Path Home

Cookbook File

Cookbook File transfers files from a subdirectory of the files/ directory of a cookbook to a specified path on the host running chef-client or solo.

The file in the cookbook is selected according to file specificity, which allows you to use a different source file based on hostname, host platform (OS or distro, as appropriate), or specific platform version. Place files under COOKBOOK_NAME/files/default to use them on any platform.

return to top of page

Actions

Action

Description

Default

create

Create this file

Yes

create_if_missing

Create only if it doesn't exist yet

 

delete

Delete this file

 

Attributes

Attribute

Description

Default Value

backup

How many backups of this file to keep. Set to false if you want no backups.

5

group

The group owner of the file (string or id)

 

mode

The octal mode of the file - e.g. '0755' default varies

 

rights

Windows Only - The user permissions. e.g. 'rights <permissions>, <principal>, <options>'. See Windows File Security.

 

inherits

Windows Only - The file inherits rights from parent. See Windows File Security.

true

owner

The owner for the file

 

path

Name attribute: The path to the file

name

source

The basename of the source file

The basename of the path (destination)

cookbook

The cookbook this file is stored in

The current cookbook

A note about mode: When specifying the mode, the value can be a quoted string, eg "644". For a numeric value (i.e., without quotes), it should be 5 digits, e.g., 00644 to ensure that Ruby can parse it correctly. For more detail, see Ticket CHEF-174.

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::CookbookFile

 

All

Examples

Transfer a file in this cookbook

Cron

Manage a cron entry. Attributes for schedule will default to '*' if not provided so only specify the schedule attributes that are applicable to your cron entry.

Create will update an entry if it shares the same name. The delete action will delete an entry with a matching name. Both notes only apply on a per-user basis.

Requires that a package providing crontab program is installed (typically cron).

return to top of page

Actions

Action

Description

Default

create

Create the crontab entry

Yes

delete

Delete the crontab entry

 

Attributes

Attribute

Description

Default Value

minute

The minute this entry should run (0 - 59)

*

hour

The hour this entry should run (0 - 23)

*

day

The day of month this entry should run (1 - 31)

*

month

The month this entry should run (1 - 12)

*

weekday

The weekday this entry should run (0 - 6) (Sunday=0)

*

command

The command to run

 

user

The user to run command as. Note: If you change the crontab user then the original user will still have the same crontab running until you explicity delete that crontab

root

mailto

Set the MAILTO environment variable

 

path

Set the PATH environment variable

 

home

Set the HOME environment variable

 

shell

Set the SHELL environment variable

 

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::Cron

 

All

Examples

Run a program on the fifth hour of the day
Run an entry if a folder exists

Deploy

The deploy resource is quite detailed and has a separate document. Please see Deploy Resource for detail on its use.

return to top of page

 

Directory

Manage a directory.

return to top of page

Actions

Action

Description

Default

create

Create this directory

Yes

delete

Delete this directory

 

Attributes

Attribute

Description

Default Value

group

The group owner of the directory (string or id)

 

mode

The octal mode of the directory, e.g. '0755' default varies

 

rights

Windows Only - The user permissions. e.g. 'rights <permissions>, <principal>, <options>'. See Windows File Security.

 

inherits

Windows Only - The directory inherits rights from parent. See Windows File Security.

true

owner

The owner for the directory

 

path

Name attribute: The path to the directory

name

recursive

When deleting the directory, delete it recursively. When creating the directory, create recursively (ie, mkdir -p). Note: owner/group/mode only applies to the leaf directory, regardless of the value of this attribute

false

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::Directory

 

All

Examples

Create a directory
Create a directory - Windows Example
Create a group of directories
Remove a directory, and its contents

Env

Manages environment keys. Currently, this is a windows-only resource.

On Unix Systems, the best way to manipulate the environment is via Ruby's ENV variable; however, manipulating this variable will not have the same "permanent" effect as using the env resource on Windows. Note that after setting an environment variable Windows requires a reboot before it is available to the Task Scheduler.

return to top of page

Actions

Action

Description

Default

create

Create new environment variable.

Yes

delete

Delete environment variable.

 

modify

Modify an existing environment variable. This will append the given value to the existing value, delimited by delim.

 

Attributes

Attribute

Description

Default Value

key_name

The name of the key to create, delete, or modify

name

value

The value to set key_name to.

 

delim

The delimiter that separates multiple values for a single key.

 

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::Env::Windows

 

Windows

Examples

Set an environment variable

Erlang Call

Connects to a distributed erlang node and makes a call. See the documentation for erl_call in the OTP documentation for more information.

Like the #Execute and #Script resources, Erlang Call resources are not idempotent. Use the not_if and only_if meta parameters to guard the resource for idempotence.

Additionally, the erl_call command needs to be on the path for this resource to work properly.

return to top of page

Actions

Action

Description

Default

run

Run this erlang call

Yes

nothing

Do not run this command

 

Attributes

Attribute

Description

Default Value

code

The erlang code to execute on the distributed node

q().

cookie

The cookie of erlang node you connect to

 

distributed

Starts a distributed erlang node if neccessary

false

name_type

Whether the node_name is an sname or name

sname

node_name

The node hostname to connect to

chef@localhost

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::ErlCall

 

All

Examples

Run a command on an erlang node

Execute

Execute a command. Use #Script resources to execute a script with a specific interpreter.

By their nature, Execute resources are not idempotent, as they are completely up to the user's imagination. Use the not_if or only_if meta parameters to guard the resource for idempotence.

return to top of page

Actions

Action

Description

Default

run

Run this command

Yes

nothing

Do not run this command

 

Use action :nothing to set a command to only run if another resource notifies it.

Attributes

Attribute

Description

Default Value

command

Name attribute: The command to execute

name

creates

If the file exists, the command will not be run. The command should create this file.

nil

cwd

Current working directory to run the command from.

nil

environment

A hash of environment variables to set before running this command.

nil

group

A group name or group ID that we should change to before running this command.

nil

path

An array of paths to use when searching for the command. Note that these are not added to the command's environment $PATH.

nil, uses system path

returns

The return value of the command (may be an array of accepted values) - this resource raises an exception if the return value(s) do not match.

0

timeout

How many seconds to let the command run before timing it out.

3600

user

A user name or user ID that we should change to before running this command.

nil

umask

Umask for files created by the command

nil

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::Execute

 

All

Examples

Execute a command, with environment variable
Execute a command only on notification
Execute a command, touch file to not run again

File

Manage files and optionally set the content. See also #CookbookFile, #Template, and #Remote File.

If you want to copy a file from a cookbook, you probably want to use #CookbookFile instead. This resource is for working with files already on your node.

return to top of page

Actions

Action

Description

Default

create

Create this file

Yes

create_if_missing

Create this file only if it does not exist. If it exists, do nothing.

 

delete

Delete this file

 

touch

Touch this file (update the mtime/atime)

 

Attributes

Attribute

Description

Default Value

path

Name attribute: The path to the file

name

backup

How many backups of this file to keep. Set to false if you want no backups.

5

group

The group owner of the file (string or id)

 

mode

The octal mode of the file - e.g. '0755' default varies

 

rights

Windows Only - The user permissions. e.g. 'rights <permissions>, <principal>, <options>'. See Windows File Security.

 

inherits

Windows Only - The file inherits rights from parent. See Windows File Security.

true

owner

The owner for the file

 

content

A string to write to the file. This will replace any previous content if set

nil (don't manage content)

A note about mode: When specifying the mode, the value can be a quoted string, eg "644". For a numeric value, it should be 5 digits, eg "00644" to ensure that Ruby can parse it correctly. For more detail, see Ticket CHEF-174.

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::File

 

All

Examples

Create a file
Create a file - Windows example
Remove a file
File Modes

Git

Git is a provider for the #SCM resource. This is closely linked with doing application code deployment, so it is documented along with the Deploy Resource.

return to top of page

 

Group

Manage a local group.

return to top of page

Actions

Action

Description

Default

create

Create the group.

Yes

remove

Remove the group.

 

modify

Modify an existing group, raising an exception if the group does not exist.

 

manage

Manage an existing group. This will take no action if the group does not exist.

 

Attributes

Attribute

Description

Default Value

group_name

Name attribute: Name of the group.

name

gid

Group id.

nil

members

Include users in a group

nil

append

true: add these members to the group, false: these are the definitive group members

false

system

true: this is a system group(system dependent low numbered range of GIDs), false: this is not a system group

nil

Providers

Provider

Shortcut Resource

Default for Platforms

Chef::Provider::Group

 

 

Chef::Provider::Group::Dscl

 

Mac OS X

Chef::Provider::Group::Gpasswd

 

All

Chef::Provider::Group::Pw

 

FreeBSD

Chef::Provider::Group::Usermod

 

Solaris

Chef::Provider::Group::Windows

 

Windows

Examples

Random user
Append to existing group

HTTP Request

Send an HTTP request with an arbitrary message. Handy for implementing your own callbacks!

return to top of page

Actions

Action

Description

Default

get

Send a GET request

Yes

put

Send a PUT request

 

post

Send a POST request

 

delete

Send a DELETE request

 

head

Send a HEAD request

 

options

Send an OPTIONS request

 

Attributes

Attribute

Description

Default Value

url

The URL to send the request to

nil

message

Name attribute: The message to be sent to the URL (as the message parameter)

name

headers

Hash of custom headers

{}

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::HttpRequest

 

All

Examples

Send a GET request
Send a POST request, with JSON message body and basic authentication
JSON Body

The message is posted as application/data and not multipart/form-data or application/x-www-form-urlencoded

Ifconfig

You can manage interfaces with the ifconfig resource. This resource is still under development.

return to top of page

Actions

Action

Description

Default

add

Run ifconfig to configure the network interface and, on some platforms, write a configuration file for the network interface.

Yes

delete

Run ifconfig to bring the network interface down and, on some platforms delete the network interface's configuration file.

 

enable

Run ifconfig to configure the network interface.

 

disable

Run ifconfig to bring the network interface down.

 

Attributes

Attribute

Description

Default Value

target

The address you would like to assign to the interface.

name

device

The network interface to be configured.

nil

hwaddr

 

nil

inet_addr

 

nil

bcast

Broadcast address. Note this is not set with ifconfig but is added to the interface's startup configuration file on select platforms.

nil

mask

The netmask.

nil

mtu

The maximum transmission unit(mtu) of the network interface.

nil

metric

The routing metric of the interface.

nil

onboot

Determines whether interface should be brought up on boot. Set to "yes" to bring interface up on boot.

nil

network

The network address.

nil

bootproto

Boot protocol, such as "dhcp"

nil

onparent

Determines whether the interface should be brought up when parent interface is brought up. Set to "yes" to bring up interface when parent interface brought up.

nil

Providers

Provider

Shortcut resource

Default For Platforms

Chef::Provider::Ifconfig

 

All

Examples

Notes

  • Currently, the default provider only writes out a start-up configuration file for the interface on Red Hat-based platforms (it writes to /etc/sysconfig/network-scripts/ifcfg-#{device_name}).

Link

Create symbolic or hard links.

return to top of page

Actions

Action

Description

Default

create

Create a link

Yes

delete

Delete a link

 

Attributes

Attribute

Description

Default Value

target_file

Name Attribute: The file name of the link

name

to

The real file you want to link to

 

link_type

Either :symbolic or :hard.

:symbolic

owner

The owner of the symlink

 

group

The group of the symlink

 

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::Link

 

All

Examples

Create a symbolic link
Create a hard link
Delete a link

Log

Adds log entries from your recipes.

return to top of page

Actions

Action

Description

Default

write

Write to log

Yes

Attributes

Attribute

Description

Default Value

level

:info, :warn, :debug, :error, or :fatal

:info

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::Log::ChefLog

n/a

All

Examples

info log level
debug log level

Mdadm

Manage mdadm software RAID devices.

return to top of page

Actions

Action

Description

Default

create

Create a new array with per-device superblocks

Yes

assemble

Assemble a previously created array into an active array

 

stop

Stop an active array

 

Attributes

Attribute

Description

Default Value

raid_device

Name attribute:The RAID device name (/dev/md0)

name

devices

An array of devices to include in the RAID array

 

level

The RAID level

1

chunk

The chunk size

16

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::Mdadm

 

Linux

Examples

Create and Assemble a RAID 1 Array from two disks with a 64k chunk size
mdadm does not create a config file
 

It is important to note that while the mdadm provider will create and assemble an array, it will not create a config file to persist the array upon reboot.
In order for that to happen, one must specify a template with the correct array layout, and use the mount provider to create an fstab entry.

 

Mount

Manage a mounted filesystem.

return to top of page

Actions

Action

Description

Default

mount

Mount the device

Yes

umount

Unmount the device

 

remount

Remount the device

 

enable

Add entry to fstab

 

disable

Remove entry from fstab

 

When passing multiple actions order matters. For example, mount must happen before enable: action [:mount, :enable]

Attributes

Attribute

Description

Default Value

mount_point

Name attribute:The directory/path where the device should be mounted

name

device

The special block device or remote node, a label or an uuid to mount.

nil

device_type

The type of the device specified. Can be :device, :label or :uuid

:device

fstype

The filesystem type of the device.

nil

options

Array or string containing mount options.

defaults

dump

Dump frequency in days, for fstab entry.

0

pass

Pass number for fsck, for fstab entry.

2

supports

A hash of options for supported mount features

{ :remount => false }

For now, device is required for umount and remount in order to check the mount command output for presence. This requirement will be removed at a later date.

For now, fstype is required. This requirement will be removed at a later date.

If options is a string, it will be converted to an array.

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::Mount

 

All, except Windows

Chef::Provider::Mount::Windows

 

Windows

Examples

Mount a local block device
Mount a remote filesystem
Mount a remote windows folder on local drive letter T:
un-mount remote windows D-drive attached as local drive letter T:
Mount a remote filesystem & add to fstab
Mount a labeled filesystem
Mount a non-block filesystem

Ohai

Reload node's ohai configuration. This allows recipes that change system attributes (e.g. add a user) to refer to those attributes later in the recipe.

return to top of page

Actions

Action

Description

Default

reload

Reload the node's ohai configuration

Yes

Attributes

Attribute

Description

Default Value

plugin

Optionally restrict reload to a particular Ohai plugin. By default, all plugins are reloaded.

nil

Providers

Provider

Shortcut Resource

Default For Platforms

Options

Chef::Provider::Ohai

 

All

 

Examples

Reload ohai
Reload ohai configuration after new user

Package

Manage packages.

return to top of page

Actions

Action

Description

Default

install

Install a package - if version is provided, install that specific version

Yes

upgrade

Upgrade a package to the latest version

 

remove

Remove a package

 

purge

Purge a package (this usually entails removing configuration files as well as the package itself)

 

Attributes

Attribute

Description

Default Value

package_name

Name attribute: The name of the package to install

name

version

The version of the package to install/upgrade

nil

response_file

An optional response file - used to pre-seed packages (note: the file is fetched by #Cookbook File)

nil

source

Used to provide an optional package source for providers that use a local file (rubygems, dpkg, yum, solaris, and rpm)

 

options

Add additional options to the underlying package command

nil

gem_binary

A gem_package attribute to specify a gem binary. Useful for installing ruby 1.9 gems while running chef in ruby 1.8

nil (API)

arch

The architecture of the package to install/upgrade (yum_package only)

nil

flush_cache

Flush the internal YumCache before/after install/upgrade (yum_package only, chef >= 0.10.4)

{ :before => false, :after => false }

allow_downgrade

Allow yum to downgrade a package to satisfy a requested version (yum_package only, chef >= 0.10.4)

false

For providers that install from a local file (rubygems, dpkg, rpm), you must first grab the file via remote_file or cookbook_file.

Providers

Provider

Shortcut Resource

Default For Platforms

Options

Chef::Provider::Package::Apt

apt_package

Debian, Ubuntu

Yes

Chef::Provider::Package::Dpkg

dpkg_package

 

Yes

Chef::Provider::Package::EasyInstall

easy_install_package

 

 

Chef::Provider::Package::Freebsd

freebsd_package

Freebsd

No

Chef::Provider::Package::Macports

macports_package

Mac OS X

No

Chef::Provider::Package::Portage

portage_package

Gentoo

Yes

Chef::Provider::Package::Rpm

rpm_package

 

Yes

Chef::Provider::Package::Rubygems

gem_package

 

Yes

Chef::Provider::Package::Rubygems

chef_gem

 

Yes

Chef::Provider::Package::Solaris

solaris_package

solaris2

Yes

Chef::Provider::Package::Yum

yum_package

Redhat, Centos

No

Chef::Provider::Package::Zypper

zypper_package

SuSE

No

The options attribute was added in 0.7.0.

Examples

Install Package
Install Specific Package Version
Install Package with options
Upgrade Package
Remove Package
Purge Package
Install Package Using Specific Provider
Install Yum package with specified architecture
Install a gem file from the local filesystem
Install a gem file only for use in Chef recipes

Use of a response file is only supported on Debian and Ubuntu at this time. Providers need to be written to support use of a response_file. On Debian and Ubuntu, the file 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 will use the #Cookbook File resource to retrieve it.

Install a package with a response_file

Gem Package Options

As of Chef 0.9.0, the RubyGems package provider attempts to install gems using RubyGems' ruby api without spawning a new gem process, but falls back to spawning a gem command to install when necessary under the following conditions:

  1. If you specify a gem_binary, the provider will run that gem command to examine its environment settings, and again to install the gem.
  2. If you specify install options as a String, the provider will spawn a gem command with those options when installing the gem.

As of Chef 0.10.10, Omnibus installs will now search the PATH for a 'gem' command rather than defaulting to the current gem environment. As part of enforce_path_sanity, the Omnibus bin directories are added to the PATH, which means if you have no other Rubygems installation preceding it in the PATH, the Omnibus Rubygems installation will still be operated against. The gem_package resource under any other installation will still default to the current gem environment unless gem_binary is provided.

Specifying Options With a Hash

If you're not using an explicit gem_binary parameter to the gem_package resource, it is preferable to provide install options as a Hash. This allows the provider to install the gem without needing to spawn an external gem process. The following options are available (options are passed to rubygems' DependencyInstaller):

Option

Description

Default Value

:env_shebang

whether or not the shebang line in executables uses /usr/bin/env ruby

false

:force

 

false

:format_executable

adds the ruby version to executables if your ruby interpreter has a trailing version number, i.e., chef-client18

false

:ignore_dependencies

 

false

:prerelease

installs prerelease gems

false

:security_policy

see http://docs.rubygems.org/read/chapter/21

nil

:wrappers

wraps executables so that you can specify which gem version to use with them

true

Installing a Gem with a Hash of Options

Specifying Options With a String

When using an explicit gem_binary, you must pass in the options as a String. When not using an explicit gem_binary, you may still pass the options as a String, but this forces chef to spawn a gem process to install the gem, using more system resources. String options are passed verbatim to the gem command, so you specify them just as you would on the command line (i.e., "--prerelease" for prerelease gems).

Installing a Gem with an Options String

Specifying Options With a .gemrc File

You can also specify options in your .gemrc file. By default the gem_package resource will use the ruby interface to install gems which will ignore the .gemrc file. You can force it to use the gem command instead, and read the .gemrc file by adding the gem_binary attribute to your block:

Installing a Gem with the gem Command

Differences between chef_gem and gem_package resources

The gem_package resource is meant to be used when installing a gem to be used on the system, and chef_gem is useful when the gem is only needed for Chef recipes. The chef_gem resource works with all of the same attributes and options as gem_package, but does not accept gem_binary because it always uses the CurrentGemEnvironment that Chef is running under. In addition to performing actions of the gem_package resource, chef_gem does the following:

  • chef_gem runs its actions immediately, before convergence, allowing you to use a gem that you just installed immediately thereafter in the recipe
  • chef_gem runs Gem.clear_paths after the action, ensuring that gem is aware of your changes so you can 'require' a gem immediately thereafter

 

PowerShell Script

#Execute a script using the PowerShell interpreter.

Includes actions/attributes available to #Execute resources: creates, cwd, environment, group, path, timeout, user. A temporary file is created and executed like other script resources, rather than run inline. This resource is used just like the regular #Script resource (and providers for bash, csh, perl, python and ruby) with some small tweaks under the covers for the Windows platform and PowerShell interpreter.

By their nature, Script resources are not idempotent, as they are completely up to the user's imagination. Use the not_if or only_if meta parameters to guard the resource for idempotence.

return to top of page

Actions

Action

Description

Default

run

Run the script

Yes

Attributes

Attribute

Description

Default Value

command

Name attribute: Name of the command to execute.

name

code

Quoted script of code to execute.

nil

interpreter

Script interpreter to use for code execution.

nil

flags

command line flags to pass to the interpreter when invoking

nil

Providers

Provider

Shortcut Resource

Chef::Provider::PowershellScript

 

All

Examples

write out to an interpolated path
use the change working directory attribute
cwd to a winodws env variable
pass an env var to script

Remote Directory

Recursively transfer a directory from the cookbook's files/default directory.

Remote directories obey file specificity so the directory you wish to copy should be located under COOKBOOK_NAME/files/default/REMOTE_DIRECTORY or a host- or distribution-specific path if desired.

Remote directory includes the attributes and actions of #Directory. Name variable is still path.

return to top of page

Attributes

Attribute

Description

Default Value

cookbook

Specify the cookbook where the directory is located, default is current cookbook

nil

files_backup

Number of backup copies to keep for files in the directory

5

files_owner

The owner for files in the directory.

nil

files_group

The group for files in the directory.

nil

files_mode

The octal mode for files in the directory - 0755.

0644

rights

Windows Only - The user permissions. e.g. 'rights <permissions>, <principal>, <options>'. See Windows File Security.

 

inherits

Windows Only - The directory inherits rights from parent. See Windows File Security.

true

path

Name attribute: Path to the directory.

name

source

From the cookbook's files/ directory.

 

purge

Purge any extra files found in the target directory

false

overwrite

Overwrite files if different from the source

true

A note about mode: When specifying the mode, the value can be a quoted string, eg "644". For a numeric value, it should be 5 digits, eg "00644" to ensure that Ruby can parse it correctly. For more detail, see Ticket CHEF-174.

Providers

Provider

Shortcut Resource

Default for Platforms

Chef::Provider::Directory::RemoteDirectory

 

All

Examples

Recursively transfer a directory from a remote location

Remote File

Deprecated Behavior

In Chef 0.8.x and earlier, Remote File is also used to fetch files from the files/ directory in a cookbook. This behavior is now provided by #Cookbook File, and use of Remote File for this purpose is deprecated (though still valid) in Chef 0.9.0 and later.

Transfer a file from a remote source. Remote File includes the attributes and actions of #File. Name variable is still path.

Read more about File Distribution to learn how Chef determines where to get the file

return to top of page

Actions

Action

Description

Default

create

Synchronize the file from the remote source to the filesystem

Yes

create_if_missing

Create the file locally by fetching from the remote source only if the file doesn't yet exist

 

Attributes

Attribute

Description

Default Value

path

Name attribute: The path to the file

name

backup

How many backups of this file to keep. Set to false if you want no backups.

5

group

(optional) The group owner of the file (string or id)

 

mode

(optional) The octal mode of the file - e.g. '0755' default varies

 

rights

Windows Only - The user permissions. e.g. 'rights <permissions>, <principal>, <options>'. See Windows File Security.

 

inherits

Windows Only - The file inherits rights from parent. See Windows File Security.

true

owner

(optional) The owner for the file

 

source

The source URL

the basename of the path attribute (see deprecated attributes)

checksum

(optional) the SHA-256 checksum of the file--if the local file matches the checksum, Chef will not download it

nil

Deprecated Attributes

The following attributes and attribute usage are relevant only to deprecated behavior that is now provided by cookbook file.

Attribute

Description

Default Value

cookbook

Specify the cookbook where the file is located, default is current cookbook

nil

source

The source file in files/ directory

last path component of name

The source follows the same search path as Templates

Providers

Provider

Shortcut Resource

Default for Platforms

Chef::Provider::File::RemoteFile

 

All

Examples

Transfer a file from some URL
Transfer a file only if the remote source has changed (uses http_request resource)

Route

Manage the system routing table.

Currently Only works on Linux, and only outputs config files on redhat based distros

return to top of page

Actions

Action

Description

Default

add

Add a route

Yes

delete

Delete a route

 

Attributes

Attribute

Description

Default Value

target

Name attribute: The address of the target route

name

netmask

The decimal representation of the network mask eg 255.255.255.0

 

gateway

The gateway for the route

 

device

Network interface to apply this route to

 

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::Route

 

All

Examples

Add a host route
Delete a network route

Ruby Block

The ruby_block resource can be used to execute a bit of Ruby code during a run. Ruby code in ruby_block resources is evaluated with other resources during convergence, whereas Ruby code outside ruby_block resources is evaluated before other resources, during recipe evaluation (compilation).

(See Evaluate and Run Resources at Compile Time for examples, and Anatomy of a Chef Run for more detail on code evaluation within a chef-client run.)

return to top of page

Actions

Action

Description

Default

create

Create the Ruby Block

Yes

Attributes

Attribute

Description

Default Value

block

A block of Ruby code

nil

Providers

Provider

Shortcut Resource

Default For Platforms

Chef::Provider::RubyBlock

 

All

Examples

Reread Chef client config in a run

SCM

Source code can be managed via the SCM resource. This is closely linked with doing application code deployment, so it is documented along with the Deploy Resource.

return to top of page

 

Script

#Execute a script using the specified interpreter. Includes all actions/attributes available to #Execute resources. Predefined available script interpreters are bash, csh, perl, python and ruby.

The ruby script resource is different than the ruby_block resource described above, as it is created as a temporary file and executed like other script resources, rather than run inline.

By their nature, Script resources are not idempotent, as they are completely up to the user's imagination. Use the not_if or only_if meta parameters to guard the resource for idempotence.

return to top of page

Actions

Action

Description

Default

run

Run the script

Yes

Attributes

Attribute

Description

Default Value

command

Name attribute: Name of the command to execute.

name

code

Quoted script of code to execute.

nil

interpreter

Script interpreter to use for code execution.

nil

flags

command line flags to pass to the interpreter when invoking

nil

Providers

Providers for Chef::Resource::Script are aliases for different command interpreters.

Provider

Shortcut Resource

Chef::Resource::Script::Bash

bash

Chef::Resource::Script::Csh

csh

Chef::Resource::Script::Perl

perl

Chef::Resource::Script::Python

python

Chef::Resource::Script::Ruby

ruby

Examples

Run a bash script
Use bash provider/interpreter to run the same script

Service

Manage a service.

return to top of page

Actions

Action

Description

Default

enable

Enable this service

 

disable

Disable this service

 

nothing

Don't do anything with this service

Yes

start

Start this service

 

stop

Stop this service

 

restart

Restart this service

 

reload

Reload the configuration for this service

 

Use action :start to make sure the service is started and running. Use action :enable to enable it at boot. See examples for more.

Attributes

Attribute

Description

Default Value

service_name

Name attribute: Name of the service.

name

pattern

Pattern to look for in the process table.

service_name

start_command

Command used to start this service.

nil

stop_command

Command used to stop this service.

nil

status_command

Command used to check the service run status.

nil

restart_command

Command used to restart this service.

nil

reload_command

Command used to tell this service to reload its configuration.

nil

supports

Features this service supports, ie :restart, :reload, :status.

false

The supports parameter attribute controls how the Chef Provider will attempt to manage the service.

  • :restart - the init script or other service provider can use a restart command. If this is not specified, Chef will attempt to stop then start the service.
  • :reload - the init script or other service provider can use a reload command.
  • :status - the init script or other service provider can use a status command to determine if the service is running. If this is not specified, Chef will attempt to match the service_name against the process table as a regular expression, unless pattern is specified as a parameter attribute.

Providers

By default, the init provider is used, which runs /etc/init.d/service_name with _command.

Provider

Shortcut Resource

Default for Platform

Chef::Provider::Service::Init

 

All

Chef::Provider::Service::Init::Debian

 

Debian, Ubuntu

Chef::Provider::Service::Upstart

 

 

Chef::Provider::Service::Init::Freebsd

 

Freebsd

Chef::Provider::Service::Init::Gentoo

 

Gentoo

Chef::Provider::Service::Init::Redhat

 

Redhat, Centos

Chef::Provider::Service::Solaris

 

Solaris

Chef::Provider::Service::Windows

 

Windows

Chef::Provider::Service::Macosx

 

Mac OS X

Examples

Starts the service if it is not running.
Basic example, starts the service if it's not running and enables it to start at system boot time
Manage the ssh service, named depending on the node's platform
Change Provider for service depending on the node's platform
Process table has a different value than the name of the service script

Subversion

Subversion is a provider for the #SCM resource. This is closely linked with doing application code deployment, so it is documented along with the Deploy Resource.

return to top of page

 

Template

Manage #File contents with an embedded ruby (erb) template. Includes actions and attributes from #File. path is the Name attribute. Read more about templates.

Templates follow the same File Specificity rules as remote_file and file resources.

return to top of page

Actions

Action

Description

Default

create

Create the file

Yes

create_if_missing

Create only if it doesn't exist yet

 

Attributes

Attribute

Description

Default Value

backup

How many backups of this file to keep. Set to false if you want no backups.

5

cookbook

Specify the cookbook where the template is located, default is current cookbook

nil

path

Name attribute: The path to the file

name

source

Template source file. Found in templates/default for the cookbook.

nil

group

The group owner of the file (string or id)

 

mode

The octal mode of the file - e.g. '0755' default varies

 

rights

Windows Only - The user permissions. e.g. 'rights <permissions>, <principal>, <options>'. See Windows File Security.

 

inherits

Windows Only - The file inherits rights from parent. See Windows File Security.

true

owner

The owner for the file

 

variables

Variables to use in the template.

 

local

Is the template already present on the node?

false

Source is found in the search path per the templates page

Providers

Provider

Shortcut Resource

Default for Platforms

Chef::Provider::File::Template

 

 

Examples

Config file from a template
Config file from a local template
Config file from a template with variable map

User

Manage a local user.

return to top of page

Actions

Action

Description

Default

create

Create the user with given attributes. If the user exists, ensure that the resource is in the correct state. This implies manage.

Yes

remove

Remove the user.

 

modify

Modify an existing user, raising an exception if the user does not exist.

 

manage

Manage an existing user. This will take no action if the user does not exist.

 

lock

Lock the user's password.

 

unlock

Unlock the user's password.

 

Attributes

Attribute

Description

Default Value

username

Name attribute: Name of the user.

name

comment

Gecos/Comment field.

nil

uid

Numeric user id.

nil

gid

Primary group id.

nil

home

Home directory location

nil

shell

Login shell.

nil

password

Shadow hash of password.

nil

system

Whether to create a system user.

nil

supports

User features supported, eg :manage_home.

{:manage_home => false, :non_unique => false }

  • The system parameter can be used with useradd as the provider to create a "system" user which passes the -r flag to useradd.
  • The supports attribute accepts a Mash where the keys represent features and the values are booleans indicating whether that particular feature is supported.
    Currently, there are two features of note:
    • :manage_home: Indicates whether the user's home directory will be created when the user is created.
      • When the Useradd provider is used, -dm wil be passed to useradd (when the :create action is used) and -d will be passed to usermod (when the :manage or :modify actions are used). If supports :manage_home=>true, the |resource user| resource does not pass the -d and -m parameters together (i.e. -dm) to usermod.
      • For the Windows provider, note that Windows doesn't create a home directory for a user until that user logs in for the first time. Further, specifying the location of the home directory using the home attribute doesn't seem to have any effect as to where Windows places the home folder.
    • :non_unique: Indicates whether non-unique UIDs are allowed.
      Currently unused by the existing providers.

Looking to add your user's public SSH key to the authorized_keys file? See the users cookbook

Providers

Provider

Shortcut Resource

Default for Platforms

Chef::Provider::User

 

 

Chef::Provider::User::Useradd

 

All

Chef::Provider::User::Pw

 

FreeBSD

Chef::Provider::User::Dscl

 

Mac OS X

Chef::Provider::User::Windows

 

Windows

Prerequisites

In order to use the "password" attribute in Chef 0.5.6, you must have "ruby-shadow" installed. You can get this by installing the debian package "libshadow-ruby1.8".

Password Shadow Hash

Different operating systems support different password encryption methods. MD5 is generally a supported fallback for the time being but newer methods such as SHA-512 should be used where available. Also, the tool you use to create the encrypted password may be different from one distribution to another.

To create a password shadow hash for use in the password attribute, run one of the following in your shell:

Create MD5 Password Shadow Hash
Create MD5 Password Shadow Hash Alternate Method

The "mkpasswd" utility can generate SHA-512 password hashes. On Ubuntu 9.10-10.04, install the mkpasswd package. On Ubuntu 10.10+, install the whois package. For other distributions, check the local documentation or package repositories.

Install mkpasswd

Then generate the password with the mkpasswd command:

Examples

Random user
System User

Opscode Cookbook LWRPs

Opscode provides several cookbooks that define custom Lightweight Resources and Providers (LWRP). They are documented on a separate page.

return to top of page

 

 

 

  1. Sep 29, 2010

    Gem package installs are timing out for me. Could there be an option in future to adjust the timeout for the package resource, or will the generic not_if override the default timeout?

  2. Oct 26, 2010

    Most versions of ruby-shadow that I have seen (including the popular one in this cookbook: http://github.com/37signals/37s_cookbooks) do not work with Ruby 1.9.x.

    I am using this: http://github.com/thoughtless/ruby-shadow-cookbook, which is a fork of http://github.com/biilmann/ruby-shadow-cookbook.

  3. Jun 14, 2011

    Anyone else curious what the difference between manage, modify and create actions are in the user resource? https://github.com/opscode/chef/blob/master/chef/lib/chef/provider/user.rb

    Might this be documented? Seems that :manage is simply :modify, but will silently do nothing if the user doesn't exit (whereas :modify complains).

    But :creates also seems to compare if the user exists, and updates accordingly, so I'm not clear on how it's different from :modify yet...

  4. Jun 14, 2011

    Ok, scratch that confusion. Here's what I've got:

    will...> create | edit | complain if nonexistent
    action
    :create – x ----- x ------------ -
    :manage – - ----- x ------------ -
    :modify – - ----- x ------------ x

  5. Jun 29, 2011

    Hi, I'm a new Chef user. I like the resource notification system, but it seems that only allows LOCAL resource notifications (doesn't support remote resource notifications), wright?

    I mean, according to this documentation ...

    The basic form of a notification is:

    resource "name" do
          notifies :action, "resource_type resource_name", :notification_timing
    end

    ... i understand that you can't specify a remote resource node. If this is correct, what is the best way in Chef to notify a remote resource?

    Thank you very much.

    Best regards,

    Leandro

    1. Jun 29, 2011

      Leandro, you right there's no real remote notifications...
      I'm curious what are you trying to achieve with a remote notification?

      For some swift recipes I've written I had to synchronize remote systems. (a file called the ring file needs to be computed in 1 place and distributed when ever it changes to all others).
      my approach was to scp the file around - either push it when it got recomputed from the source, or pull it when a node was checking for an updated.

      Another possible approach is to store information as either node attributes or data_bags.

      Both the approaches assume that each machine runs chef-client as a daemon, and that there's no immediacy required - i.e. that its ok to pick the change the next interval (10 minutes or so)

    2. Jun 29, 2011

      I'm still finding my groove with chef (so maybe someone else can comment on how much of a bad idea this is) but if its only one node that needs to run remote notifications on other nodes, perhaps you could make that node into an admin client, and so write to databags from within its recipes. Then right after update, you could ssh over to other nodes (whose identity is perhaps determined through search()) and run chef-client on-demand to act on the new data_bag content.

      Not sure when solr indexes the new databag changes, so that might be a caveat.

      I'm sure this isn't how chef is intended to be used, and I imagine there's a more elegant solution, but hey, might get you thinking along the right lines (smile)

      1. Jun 29, 2011

        Hi Andi and Patrick, thank you very much for your quick and useful responses! I'm thinking in how handle clusters configurations with Chef when a new node is added to the cluster, and therefore I need refresh the configuration in the cluster's clients. For example, suppose that we have 2 memory cache servers (i.e running Memcached) in one cluster and have one (or more) web servers that use these cache servers (in this scenario the web servers are "clients" of the cache servers). If I add a third Memcached server to the cluster I will need update the web server configuration (their php configuration and reload the web servers).
        I think that the two approachs you suggested can work perfect (the "push" strategy of use scp/ssh to send/refresh a new configuration or the "pull" strategy of use data bags and wait until the web servers chef clients refresh their configurations).
        Howerver, perhaps the use of notifications is not the best approach in this situation. Maybe is a too "event-driven" solution and a more declarative approach could be better. I'm just starting with Chef and have a lot to learn. Anyway, I'm sure these strategies are very useful in many scenarios.

        Thank you very much again for your help folks!

        1. Jun 29, 2011

          Actually, the scenario you're describing is very similar to what the swift-proxy code needed to do. down to the memcache servers (wink)

          take a peek here: https://github.com/dellcloudedge/openstack-swift/blob/master/cookbooks/swift/recipes/proxy.rb

          The assumption here is that the new servers can be picked up "soon". Each server runs this code independently and uses the Chef database to locate it's friends (in my case each server runs a memcached server as well.. but can utilize the peer ones). If any new servers are present, the local configuration is updated, and the service restarted.

          Key points here -
          a) it happens independently on each server, the next time the chef-client daemon is executed
          b) chef (server) knows about the roles (and hence capabilities) each server has. clients can query the server and use this knowledge to self configure

          1. Jun 29, 2011

            Thank you very much Andi. I read the swift-proxy recipe, is a very good example. Like I can see, there is no need to use notifications in these situations. Using roles and searchs is all what I need. Thank you again!

            Leandro

            1. Jun 29, 2011

              Actually, Leandro, you pointed out a bug, or at least made me realize one exists.

              Assuming the service in question only reads its configuration when it starts, the template code should notify the service to restart if changes were made (Chef is smart enough to only fire the notification if the template actually changed)
              I'll put a fix for that in a bit.

  6. Jul 29, 2011

    The mode doesn't have to be five digits, it just has to have a leading 0 (zero).