Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Chef Infrastructure Automation Cookbook Second Edition
Chef Infrastructure Automation Cookbook Second Edition

Chef Infrastructure Automation Cookbook Second Edition: Over 80 recipes to automate your cloud and server infrastructure with Chef and its associated toolset

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Chef Infrastructure Automation Cookbook Second Edition

Chapter 2. Evaluating and Troubleshooting Cookbooks and Chef Runs

"Most people spend more time and energy going around problems than in trying to solve them."

Henry Ford

In this chapter, we'll cover the following recipes:

  • Testing your Chef cookbooks
  • Flagging problems in your Chef cookbooks
  • Test-driven development for cookbooks using ChefSpec
  • Integration testing your Chef cookbooks with Test Kitchen
  • Showing affected nodes before uploading cookbooks
  • Overriding a node's run list to execute a single recipe
  • Using why-run mode to find out what a recipe might do
  • Debugging Chef client runs
  • Inspecting the results of your last Chef run
  • Raising and logging exceptions in recipes
  • Diff-ing cookbooks with knife
  • Using community exception and report handlers
  • Creating custom handlers

Introduction

Developing cookbooks and making sure your nodes converge to the desired state is a complex endeavor. You need transparency about what is really happening. This chapter will cover a lot of ways to see what's going on and make sure that everything is working as it should. From running basic checks on your cookbooks to a fully test driven development approach, we'll see what the Chef ecosystem has to offer.

Testing your Chef cookbooks

You know how annoying this is: you tweak a cookbook, upload it to your Chef server, start a Chef run on your node and, boom! It fails. What's even more annoying is that it fails not because a black hole absorbed your node and the whole data center that node lives in, but because you missed a mundane comma in the default recipe of the cookbook you just tweaked. Fortunately, there's a very quick and easy way to find such simple glitches before you go all in and try to run your cookbooks on real nodes.

Getting ready

Install the ntp cookbook by running the following code:

mma@laptop:~/chef-repo $ knife cookbook site install ntp
Installing ntp to /Users/mma/work/chef-repo/cookbooks
…TRUNCATED OUTPUT…
Cookbook ntp version 1.7.0 successfully installed

How to do it...

Carry out the following steps to test your cookbooks:

  1. Run knife cookbook test on a working cookbook, for example, the ntp cookbook:
    mma@laptop:~/chef-repo $ knife cookbook test ntp
    
    checking...

Flagging problems in your Chef cookbooks

Writing solid Chef recipes can be quite challenging. There are a couple of pitfalls, which you can easily overlook. Also, writing cookbooks in a consistent style is even harder. You might wonder what the proven ways to write cookbooks are. Foodcritic tries to identify possible issues with the logic and style of your cookbooks.

In this section, you'll learn how to use Foodcritic on some existing cookbooks.

Getting ready

Install the mysql cookbook by running the following code:

mma@laptop:~/chef-repo $ knife cookbook site install mysql 6.0.0
Installing mysql to /Users/mma/work/chef-repo/cookbooks
…TRUNCATED OUTPUT…
Cookbook mysql version 6.0.0 successfully installed

How to do it...

Let's see how Foodcritic reports findings:

  1. Run foodcritic on your cookbook:
    mma@laptop:~/chef-repo $ foodcritic ./cookbooks/my
    sql
    
    ...TRUNCATED OUTPUT...
    FC001: Use strings in preference to symbols to access node attributes: ./cookbooks/mysql/libraries/helpers...

Test-driven development for cookbooks using ChefSpec

Test-driven development (TDD) is a way to write unit tests before writing any recipe code. By writing the test first, you design what your recipe should do and ensure that your test is for real because it should fail, as long as you haven't written your recipe code.

As soon as you've completed your recipe, your unit tests should pass.

ChefSpec is built on the popular RSpec framework and offers a tailored syntax to test Chef recipes.

Let's develop a very simple recipe using the TDD approach with ChefSpec.

Getting ready

Make sure you have a cookbook called my_cookbook and run_list of your node includes my_cookbook, as described in the Creating and using cookbooks recipe in Chapter 1, Chef Infrastructure.

How to do it...

Let's write a failing test first and then a recipe, which will pass the test:

  1. Create the spec directory for your cookbook:
    mma@laptop:~/chef-repo $ mkdir cookbooks/my_cookbook/spec
    
  2. Create your spec file:
    mma@laptop...

Integration testing your Chef cookbooks with Test Kitchen

Verifying that your cookbooks really work when converging a node is essential. Only if you can trust your cookbooks, you are ready to run them anytime on your production servers.

Test Kitchen is Chef's integration testing framework. It enables you to write tests, which run after a VM is instantiated and converged, using your cookbook. Your tests run in that VM and can verify that everything works as expected.

This is in contrast to ChefSpec, which only simulates a Chef run. Test Kitchen boots up a real node and runs Chef on it. Your tests see the real thing.

Let's see how you can write such integration tests for your cookbooks.

Getting ready

Make sure you have a cookbook named my_cookbook, as described in the Creating and using cookbooks recipe in Chapter 1, Chef Infrastructure.

Make sure you have Vagrant installed, as described in the Managing virtual machines with Vagrant recipe in Chapter 1, Chef Infrastructure.

How to do it...

Showing affected nodes before uploading cookbooks

You know how it goes. You tweak a cookbook to support your new server and upload it to your Chef server. Your new node converges just fine and you're happy. Well, until your older production server picks up your modified cookbook during an automated Chef client run and spits its guts at you. Obviously, you forgot that your old production server was still using the cookbook you tweaked. Luckily, there is the knife preflight command, which can show you all the nodes using a certain cookbook before you upload it to your Chef server.

Getting ready

For the following example, we assume that you have at least one role using the ntp cookbook in its run list and that you have multiple servers with this role and/or the ntp cookbook in their run list directly.

Use Chef to install the knife-preflight gem:

mma@laptop:~/chef-repo $ chef gem install knife-preflight
Fetching gem metadata from https://rubygems.org/
...TRUNCATED OUTPUT...
Installing knife...

Introduction


Developing cookbooks and making sure your nodes converge to the desired state is a complex endeavor. You need transparency about what is really happening. This chapter will cover a lot of ways to see what's going on and make sure that everything is working as it should. From running basic checks on your cookbooks to a fully test driven development approach, we'll see what the Chef ecosystem has to offer.

Testing your Chef cookbooks


You know how annoying this is: you tweak a cookbook, upload it to your Chef server, start a Chef run on your node and, boom! It fails. What's even more annoying is that it fails not because a black hole absorbed your node and the whole data center that node lives in, but because you missed a mundane comma in the default recipe of the cookbook you just tweaked. Fortunately, there's a very quick and easy way to find such simple glitches before you go all in and try to run your cookbooks on real nodes.

Getting ready

Install the ntp cookbook by running the following code:

mma@laptop:~/chef-repo $ knife cookbook site install ntp
Installing ntp to /Users/mma/work/chef-repo/cookbooks
…TRUNCATED OUTPUT…
Cookbook ntp version 1.7.0 successfully installed

How to do it...

Carry out the following steps to test your cookbooks:

  1. Run knife cookbook test on a working cookbook, for example, the ntp cookbook:

    mma@laptop:~/chef-repo $ knife cookbook test ntp
    
    checking ntp
    Running syntax...

Flagging problems in your Chef cookbooks


Writing solid Chef recipes can be quite challenging. There are a couple of pitfalls, which you can easily overlook. Also, writing cookbooks in a consistent style is even harder. You might wonder what the proven ways to write cookbooks are. Foodcritic tries to identify possible issues with the logic and style of your cookbooks.

In this section, you'll learn how to use Foodcritic on some existing cookbooks.

Getting ready

Install the mysql cookbook by running the following code:

mma@laptop:~/chef-repo $ knife cookbook site install mysql 6.0.0
Installing mysql to /Users/mma/work/chef-repo/cookbooks
…TRUNCATED OUTPUT…
Cookbook mysql version 6.0.0 successfully installed

How to do it...

Let's see how Foodcritic reports findings:

  1. Run foodcritic on your cookbook:

    mma@laptop:~/chef-repo $ foodcritic ./cookbooks/my
    sql
    
    ...TRUNCATED OUTPUT...
    FC001: Use strings in preference to symbols to access node attributes: ./cookbooks/mysql/libraries/helpers.rb:273
    FC005: Avoid...

Test-driven development for cookbooks using ChefSpec


Test-driven development (TDD) is a way to write unit tests before writing any recipe code. By writing the test first, you design what your recipe should do and ensure that your test is for real because it should fail, as long as you haven't written your recipe code.

As soon as you've completed your recipe, your unit tests should pass.

ChefSpec is built on the popular RSpec framework and offers a tailored syntax to test Chef recipes.

Let's develop a very simple recipe using the TDD approach with ChefSpec.

Getting ready

Make sure you have a cookbook called my_cookbook and run_list of your node includes my_cookbook, as described in the Creating and using cookbooks recipe in Chapter 1, Chef Infrastructure.

How to do it...

Let's write a failing test first and then a recipe, which will pass the test:

  1. Create the spec directory for your cookbook:

    mma@laptop:~/chef-repo $ mkdir cookbooks/my_cookbook/spec
    
  2. Create your spec file:

    mma@laptop:~/chef-repo ...

Integration testing your Chef cookbooks with Test Kitchen


Verifying that your cookbooks really work when converging a node is essential. Only if you can trust your cookbooks, you are ready to run them anytime on your production servers.

Test Kitchen is Chef's integration testing framework. It enables you to write tests, which run after a VM is instantiated and converged, using your cookbook. Your tests run in that VM and can verify that everything works as expected.

This is in contrast to ChefSpec, which only simulates a Chef run. Test Kitchen boots up a real node and runs Chef on it. Your tests see the real thing.

Let's see how you can write such integration tests for your cookbooks.

Getting ready

Make sure you have a cookbook named my_cookbook, as described in the Creating and using cookbooks recipe in Chapter 1, Chef Infrastructure.

Make sure you have Vagrant installed, as described in the Managing virtual machines with Vagrant recipe in Chapter 1, Chef Infrastructure.

How to do it...

Let's create...

Showing affected nodes before uploading cookbooks


You know how it goes. You tweak a cookbook to support your new server and upload it to your Chef server. Your new node converges just fine and you're happy. Well, until your older production server picks up your modified cookbook during an automated Chef client run and spits its guts at you. Obviously, you forgot that your old production server was still using the cookbook you tweaked. Luckily, there is the knife preflight command, which can show you all the nodes using a certain cookbook before you upload it to your Chef server.

Getting ready

For the following example, we assume that you have at least one role using the ntp cookbook in its run list and that you have multiple servers with this role and/or the ntp cookbook in their run list directly.

Use Chef to install the knife-preflight gem:

mma@laptop:~/chef-repo $ chef gem install knife-preflight
Fetching gem metadata from https://rubygems.org/
...TRUNCATED OUTPUT...
Installing knife-preflight...

Overriding a node's run list to execute a single recipe


We all have those snowflake environments that are built using Chef, but we're not comfortable with running the Chef client anymore. We know that some cookbooks have been enhanced but never tested against this specific environment. The risk of bringing it down by a Chef client run is pretty high.

However, even though we do not dare do a full Chef client run, we might need to run, for example, the users cookbook, in order to add a new colleague to our snowflake environment. This is where Chef client's feature to override a run list to execute a single recipe comes in very handy.

Note

Don't overuse this feature! Make sure you fix your environment so that you're comfortable to run Chef client whenever you need to!

Getting ready

To follow along with the following example, you'll need a node hooked up to your Chef server having multiple recipes and/or roles in its run list.

How to do it...

Let's see how to run a single recipe out of a bigger run...

Using why-run mode to find out what a recipe might do


why-run mode lets each resource tell you what it would do during a Chef client run, assuming certain prerequisites. This is great because it gives you a glimpse about what might really happen on your node when you run your recipe for real.

However, because Chef converges a lot of resources to a desired state, why-run will never be accurate for a complete run. Nevertheless, it might help you during development while you're adding resources step-by-step to build the final recipe.

In this section, we'll try out why-run mode to see what it tells us about our Chef client runs.

Getting ready

To try out why-run mode, you need a node where you can execute the Chef client and at least one cookbook that is available on that node.

How to do it...

Let's try to run the ntp cookbook in why-run mode:

  1. Override the current run list to run the ntp recipe in why-run mode on a brand new box:

    user@server:~$ sudo chef-client -o 'recipe[ntp]' --why-run
    
    ...TRUNCATED...
Left arrow icon Right arrow icon

Description

This book is for system engineers and administrators who have a fundamental understanding of information management systems and infrastructure. It helps if you've already played around with Chef; however, this book covers all the important topics you will need to know. If you don't want to dig through a whole book before you can get started, this book is for you, as it features a set of independent recipes you can try out immediately.

What you will learn

  • Set up your local development and testing environment for Chef
  • Debug your cookbooks and Chef runs by using the numerous inspection and logging facilities of Chef
  • Drive your cookbooks from external data or nodespecific attributes
  • Manage and scale your cloud infrastructure by automating your configuration management
  • Extend Chef to meet your advanced needs by creating custom plugins for knife and Ohai
  • Test your Chef cookbooks and infrastructure by writing examples

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 29, 2015
Length: 278 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287947
Vendor :
Chef
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : May 29, 2015
Length: 278 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287947
Vendor :
Chef
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 73.98
Chef Infrastructure Automation Cookbook Second Edition
€36.99
Mastering Chef
€36.99
Total 73.98 Stars icon
Banner background image

Table of Contents

8 Chapters
1. Chef Infrastructure Chevron down icon Chevron up icon
2. Evaluating and Troubleshooting Cookbooks and Chef Runs Chevron down icon Chevron up icon
3. Chef Language and Style Chevron down icon Chevron up icon
4. Writing Better Cookbooks Chevron down icon Chevron up icon
5. Working with Files and Packages Chevron down icon Chevron up icon
6. Users and Applications Chevron down icon Chevron up icon
7. Servers and Cloud Infrastructure Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7
(6 Ratings)
5 star 50%
4 star 16.7%
3 star 0%
2 star 16.7%
1 star 16.7%
Filter icon Filter
Top Reviews

Filter reviews by




Michael Aug 08, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really like this book so far. I was concerned that the recipe format would not be best for a beginner but it has great step-by-step guides in here that will bring you up to speed quickly. Highly recommend for those just learning Chef.
Amazon Verified review Amazon
John D. Aug 09, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It helps to have a basic understanding of how Chef works before this book is really valuable, and this book could be summed up as chapters full of bite-sized mini-HOWTOs that help you get from basic knowledge to really knowing your way around.I use Chef a lot, and really enjoyed reading the first edition of this book, and I hadn't used Chef a whole ton back then. Upon reading the second edition, I'm still able to have some "a-ha" moments, and further my understanding. Another great way to think about this book is a substitute for the Chef documentation - it's a great cheat sheet for some of the most common tasks you'll perform.Some of the only quirks (should only impact novice to intermediate users):- the lack of visual representations, but this will matter a lot less if you have some experience- the mini-HOWTO (my description) sections have 'how it works' subsections at the end - you may want to skip ahead if things don't make sense- it would also really help to have a basic understanding of git and vagrant before startingSide note: this is in the upper 5% of Packt Publishing books I've readTL;DR: a must-have resource for any Chef user, and the only books that compare in any way are the O'Reilly books on Chef
Amazon Verified review Amazon
Antonio Dec 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very helpful reading. I have worked with Ansible an Salt before and this book got me up to speed with Chef. Of course, it's not deeply elaborating specific points but if you already have knowledge of configuration management this will help you to catch up quickly.
Amazon Verified review Amazon
Jean Remy Aug 05, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book has a lot of great examples which helped me tremendously testing some of the recipes. As an intermediate user it was fairly easy to work my way through the chapters. However, this book is not for a novice user since it does not have a lot of diagrams to explain visually the overall intent of each recipes.
Amazon Verified review Amazon
Matthew Dresden Dec 21, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
This is too far out of date to be of any practical use, but unfortunately this is the case for all Chef books.Chefs docs and Github are the only place worth looking at, plus someone who already knows chef.It would otherwise be a very long painful process to real use chef appropriately.It advises against wrapping, which is now the standard.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.