Information Technology Reference
In-Depth Information
Chef Syntax and Examples
The
Domain Specific Language
(DSL) used by Chef is actually just a subset of Ruby. The
full power of the Ruby programming language is accessible in Chef code. This allows deve-
lopers to conditionally perform actions, perform mathematical operations, and communicate
with other services easily from within Chef code. Before diving into the more advanced fea-
tures of Chef's DSL, we will explore the basic syntax first.
Here is an example of the Chef DSL in action, demonstrating how a user account can be cre-
ated with a Chef resource. In Chef, resources are the building blocks used to define specific
parts of your infrastructure. For example, the following statement manages a user account
named
alice
with a user identifier (UID) of 503:
user
'alice'
ddo
uid
'503'
end
end
The following code sample demonstrates the more abstract syntax for invoking a DSL meth-
od in Chef code, on which the previous example is based:
resource
'NAME'
ddo
parameter1
value1
parameter2
value2
end
The first part is the name of the resource (such as
template
,
package
, or
service
). The
next part is the
name_attribute
for that resource. The interpretation of this value changes
from resource to resource. For example, in the
package
resource, the
name_attribute
is the
name of the package you wish to install. In the
template
resource, the
name_attribute
is
the path on the target node where the compiled file should reside. Next comes the Ruby
keyword
do
. In Ruby, the
do
must always be accompanied by a closing
end
. Everything that
resides between the
do
and
end
is called the
block
. Inside the block, resource parameters and
their values are declared. This varies from resource to resource. A valid parameter for the
package
provider is
version
, whereas a valid parameter for the
template
provider is
source
.