The Scenario
We continue to utilize Chef in our organization’s infrastructure, and it’s time to create a cookbook that installs Nginx. Creating new web servers, for either production or internal testing, is fairly common. We’d like to be able to control the run-list for all web server nodes in a single place though, and we’ve decided that we will use a new role to do this. After we’ve written our Nginx cookbook, we’ll deploy it to the first web server node using a role.
Logging in
On the lab overview page, we’ll see three EC2 instances: a Chef server ( we’ll call it chef
), a workstation (we’ll call it worker
) and a node (we’ll call it node
). The shell prompts in this lab guide will reflect which one we’re running commands in at the moment.
Get Nginx Running and Enabled on web-node1
We need to write a cookbook that installs the Nginx package and starts the service. This cookbook needs to be published and the recipe run on web-node1
.
Create the Cookbook
After logging into worker
, we can get into the provided Chef repository right away, with cd chef-repo
. Once we’re in there, we can start building our cookbook:
|
|
Create the Recipe
Edit the file ./cookbooks/nginx/recipes/default.rb
with whichever text editor you like. When we’re done, the file should read like this (after our additions, and once we’ve removed the comments that were sitting in there already):
|
|
Loading Our Cookbook
If we run this:
|
|
and then this:
|
|
we’ll see our web-node1
listed.
Create the webserver
Role, and Ensure It Includes Nginx
We have to create a new role called webserver
for installing Nginx and running the service. On this machine though, we don’t have a default editor set, so we’ll get an error if try we creating the role first. We’re going to set Vim here, and then create the role:
|
|
Now we’ll land in Vim, editing some JSON. Make the run_list
section look like this:
|
|
Use the webserver
Role in the web-node1
Run-list
Let’s set the webserver
role to this node:
|
|
Now we can run our changes and push our cookbook up to the chef
machine:
|
|
We’ll be prompted for our password a couple of times (which will be the same as the cloud_user
password we used for getting into the machine in the first place) and then we can watch the command output all of the things going on. As a sanity check, we should run the command again though. If nothing actually happens, then it means all went well. We should have gotten Nginx installed and started the first time around.
Conclusion
Now, we can run this:
|
|
And we’ll see that our node is using a role, instead of a recipe directly. Since this is exactly how we wanted things to be running, we’re done. Congratulations!