Cookbooks are an essential part of Chef. You can easily create them using the Chef executable installed by the Chef DK. In this recipe (and many of the following recipes), I will assume that you're using a Chef server to manage your infrastructure. You can either set up your own cookbook or use the hosted Chef as described previously. You'll use the command-line tool knife to interact with the Chef server.
In this recipe, we'll create and apply a simple cookbook using the Chef and knife command-line tools.
Make sure you have Chef DK installed and a node available for testing. Check out the installation instructions at http://learn.chef.io if you need help here.
knife.rb file (usually found in the hidden
.chef directory) and add the following three lines to it, filling in your own values:
cookbook_copyright "your company" cookbook_license "apachev2" cookbook_email "your email address"
The Apache 2 license is the most commonly found in cookbooks, but you're free to choose whichever suits your needs. If you put
cookbook_license, knife will put
"All rights reserved" into your recipe's metadata file.
We assume that you have a node called
server registered with your Chef server, as described in the Managing virtual machines with Vagrant section in this chapter.
Carry out the following steps to create and use cookbooks:
Create a cookbook named
my_cookbookby running the following command:
mma@laptop:~/chef-repo $ chef generate cookbook cookbooks/my_cookbook
Compiling Cookbooks... Recipe: code_generator::cookbook ...TRUNCATED OUTPUT...
Before ChefDK was introduced, the only way to generate cookbooks was to use
knife cookbook create my_cookbook
Upload your new cookbook on the Chef server:
mma@laptop:~/chef-repo $ knife cookbook upload my_cookbook
Uploading my_cookbook [0.1.0] Uploaded 1 cookbook.
Add the cookbook to your node's run list. In this example, the name of the node is server:
mma@laptop:~/chef-repo $ knife node run_list add server 'recipe[my_cookbook]'
server: run_list: recipe[my_cookbook]
user@server:~$ sudo chef-client
Knife is the command-line interface for the Chef server. It uses the RESTful API exposed by the Chef server to do its work and helps you to interact with the Chef server.
The knife command supports a host of commands structured as follows:
knife <subject> <command>
<subject> used in this section is either
node. The commands we use are
upload for the cookbook, and
run_list add for the node.