About Definitions

Warning

Starting with chef-client 12.5, it is recommended to build custom resources instead of definitions. While the use of definitions is not deprecated—all existing definitions will continue to work—it is recommended to also migrate existing definitions to the new custom resource patterns. This topic introduces definitions as they once were (and still can be, if desired), but deprecates all but one example of using them in favor of showing how to migrate an existing definition to the new custom resource pattern.

A definition behaves like a compile-time macro that is reusable across recipes. A definition is typically created by wrapping arbitrary code around resources that are declared as if they were in a recipe. A definition is then used in one (or more) actual recipes as if the definition were a resource.

Though a definition looks like a resource, and at first glance seems like it could be used interchangeably, some important differences exist. A definition:

Is not a resource or a custom resource

Is processed while the resource collection is compiled (whereas resources are processed while a node is converged)

Does not support common resource properties, such as notifies, subscribes, only_if, and not_if

Is defined from within the /definitions directory of a cookbook

Does not support why-run mode

Syntax (pre-12.5)

A definition has four components:

A resource name

Zero or more arguments that define parameters their default values; if a default value is not specified, it is assumed to be nil

A hash that can be used within a definition’s body to provide access to parameters and their values

host_porter node['hostname'] do
port 4000
end
host_porter 'www1' do
port 4001
end

Examples

The following examples show how to use cookbook definitions.

Many Recipes, One Definition

Warning

With the improved custom resource pattern available starting with chef-client 12.5, the need to use definitions is greatly minimized. In every case when considering to use a definition, first evaluate whether that defintion is better represented as a custom resource.

Data can be passed to a definition from more than one recipe. Use a definition to create a compile-time macro that can be referenced by resources during the converge phase. For example, when both /etc/aliases and /etc/sudoers require updates from multiple recipes during a single chef-client run.

Once built, the custom resource may be used in a recipe just like the any of the resources that are built into Chef. The resource gets its name from the cookbook and from the file name in the /resources directory, with an underscore (_) separating them. For example, a cookbook named host with a custom resource in the /resources directory named porter.rb. Use it in a recipe like this: