Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Chef Cookbook
Chef Cookbook

Chef Cookbook: Achieve powerful IT infrastructure management and automation , Third Edition

Arrow left icon
Profile Icon Marschall
Arrow right icon
$9.99 $39.99
eBook Feb 2017 268 pages 3rd Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Marschall
Arrow right icon
$9.99 $39.99
eBook Feb 2017 268 pages 3rd Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Chef Cookbook

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 with cookstyle and Rubocop
  • Flagging problems in your Chef cookbooks with Foodcritic
  • Test-driven development for cookbooks using ChefSpec
  • Compliance testing with InSpec
  • 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 chef-shell
  • Using why-run mode to find out what a recipe might do
  • Debugging Chef client runs
  • Inspecting the results of your last Chef run
  • Using Reporting to keep track of all your Chef client runs
  • Raising and logging exceptions in recipes
  • Diff-ing cookbooks with knife
  • Using community exception and...

Introduction

Developing cookbooks and making sure your nodes converge to the desired state is a complex endeavor. You need transparency about what is 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 with cookstyle and Rubocop

You know how annoying this is: you tweak a cookbook, run Test Kitchen, and, boom! it fails. What's even more annoying is that it fails only 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 Test Kitchen.

Getting ready

Install the ntp cookbook by running the following command:

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

How to do it…

Carry out the following steps to test your cookbook; run cookstyle on the ntp cookbook:

mma@laptop:~/chef-repo $ cookstyle cookbooks/ntp
Inspecting 5 files
...C.

Offenses:

cookbooks/ntp/recipes/default.rb:25:1: C: Extra blank line detected.

5 files inspected, 1 offense detected...

Flagging problems in your Chef cookbooks with Foodcritic

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 version 6.0.0 of 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/mysql
    ...TRUNCATED OUTPUT...
    FC001: Use strings in preference to symbols to access node attributes: ./cookbooks/mysql/libraries/helpers.rb:273
    FC005: Avoid repetition of resource declarations: ./cookbooks/mysql/libraries/provider_mysql_service.rb:77
    ...TRUNCATED OUTPUT...

Introduction


Developing cookbooks and making sure your nodes converge to the desired state is a complex endeavor. You need transparency about what is 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 with cookstyle and Rubocop


You know how annoying this is: you tweak a cookbook, run Test Kitchen, and, boom! it fails. What's even more annoying is that it fails only 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 Test Kitchen.

Getting ready

Install the ntp cookbook by running the following command:

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

How to do it…

Carry out the following steps to test your cookbook; run cookstyle on the ntp cookbook:

mma@laptop:~/chef-repo $ cookstyle cookbooks/ntp
Inspecting 5 files
...C.

Offenses:

cookbooks/ntp/recipes/default.rb:25:1: C: Extra blank line detected.

5 files inspected, 1 offense detected 

How it works…

Cookstyle is...

Flagging problems in your Chef cookbooks with Foodcritic


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 version 6.0.0 of 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/mysql
    ...TRUNCATED OUTPUT...
    FC001: Use strings in preference to symbols to access node attributes: ./cookbooks/mysql/libraries/helpers.rb:273
    FC005: Avoid repetition of resource declarations: ./cookbooks/mysql/libraries/provider_mysql_service.rb:77
    ...TRUNCATED OUTPUT...
    
  2. Get a detailed list of the...

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. Then, you ensure that your test fails, while you haven't written your recipe code.

As soon as you've completed your recipe, your unit tests should pass. You can be sure that your recipe works as expected – even if you decide to refactor it later to make it more readable.

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 the 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. Then we will write a recipe that satisfies the test:

  1. Create your spec file:

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

Compliance testing with InSpec


Verifying that servers and applications you install are configured correctly and fulfill all compliance requirements by hand is tedious and error-prone. Chef comes with InSpec, a human-readable language for compliance auditing and testing your infrastructure. With InSpec, you can write automated tests to verify a host of criteria on your servers: from the contents of certain files to applications running on certain ports, you can make sure that your servers and applications are configured correctly.

Getting ready

Make sure you have ChefDK installed, as described in the Installing the Chef Development Kit on your workstation recipe in Chapter 1, Chef Infrastructure.

How to do it…

Let's create a very simple compliance requirement as code and run it on your local workstation:

  1. Create a new profile for your InSpec tests:

    mma@laptop:~/chef-repo $ inspec init profile my_profile
    Create new profile at /Users/mma/work/chef-repo/my_profile
     * Create directory controls
     * Create...

Integration-testing your Chef cookbooks with Test Kitchen


Verifying that your cookbooks actually work when converging a node is essential. Only when you know that you can rely on your cookbooks, are you 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 InSpec tests run by Test Kitchen 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 on your workstation, as described in the Managing virtual machines with Vagrant...

Showing affected nodes before uploading cookbooks


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 throws a fit. 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 multiple servers with the ntp cookbook in their run list (either directly or via roles).

Use Chef to install the knife-preflight gem. It contains the preflight plugin extending knife with additional commands:

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

How to do it...

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


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

Note

Only use this feature when you absolutely must! It is bad practice because it breaks the principles of desired state config and single source of truth.

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 list on your node:

  1. Show the data for your node. In this example, the node has the role base in its run list. Depending on your setup, you'll find other data here:

    mma@laptop:~/chef-repo $ knife node show www.example.com
    ...TRUNCATED OUTPUT…
    Run List:    role[base]
    Roles:       base
    Recipes...

Using chef-shell


While writing cookbooks, being able to try out parts of a recipe interactively and using breakpoints helps you to understand how your recipes work.

Chef comes with chef-shell, which is essentially an interactive Ruby session with Chef. In chef-shell, you can create attributes, write recipes, and initialize Chef runs, among other things. Chef-shell allows you to evaluate parts of your recipes on-the-fly before uploading them to your Chef server.

How to do it…

Running chef-shell is straightforward:

  1. Start chef-shell in standalone mode:

    mma@laptop:~/chef-repo $ chef-shell
    loading configuration: none (standalone chef-shell session)
    Session type: standalone
    Loading......done.
    
    This is the chef-shell.
     Chef Version: 12.14.89
     http://www.chef.io/
     http://docs.chef.io/
    
    run `help' for help, `exit' or ^D to quit.
    
    Ohai2u mma@laptop!
    chef (12.14.89)>
    
  2. Switch to the attributes mode in chef-shell:

    chef (12.14.89)> attributes_mode
    
  3. Set an attribute value to be used inside the recipe later...

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 of 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 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 OUTPUT......

Debugging Chef client runs


Sometimes you get obscure error messages when running the Chef client and you have a hard time finding any clue about where to look for the error. Is your cookbook broken? Do you have a networking issue? Is your Chef server down? Only by looking at the most verbose log output do you have a chance to find out.

Getting ready

You need a Chef client hooked up to the hosted Chef or your own Chef server.

How to do it…

To see how we can ask the Chef client to print debug messages, run the Chef client with debug output:

user@server:~$ sudo chef-client -l debug
...TRUNCATED OUTPUT...
[2016-11-14T07:57:36+00:00] DEBUG: Sleeping for 0 seconds
[2016-11-14T07:57:36+00:00] DEBUG: Running Ohai with the following configuration: {:log_location=>#<IO:<STDOUT>>, :log_level=>:debug, ...TRUNCATED OUTPUT...
 [2016-11-14T07:57:37+00:00] DEBUG: Plugin C: ran 'cc -V -flags' and returned 1
[2016-11-14T07:57:37+00:00] DEBUG: Plugin C 'cc -V -flags' failed. Skipping data.
[2016...

Inspecting the results of your last Chef run


When developing new cookbooks, we need to know what exactly went wrong when a Chef client run fails.

Even though Chef prints all the details to stdout, you might want to look at it again, for example, after clearing your shell window.

Getting ready

You need to have a broken cookbook in your node's run list; any invalid piece of Ruby code will do:

Nil.each {}

How to do it...

Carry out the following steps:

  1. Run the Chef client with your broken cookbook:

    user@server:~$ sudo chef-client
    ================================================================================
    Recipe Compile Error in /var/chef/cache/cookbooks/my_cookbook/recipes/default.rb
    ================================================================================
    NoMethodError
    -------------
    undefined method `each' for nil:NilClass
    
    Cookbook Trace:
    ---------------
      /var/chef/cache/cookbooks/my_cookbook/recipes/default.rb:7:in `from_file'
    
    Relevant File Content:
    ----------------------
    /var/chef...

Using Reporting to keep track of all your Chef client runs


You need to know what exactly happened on your servers. If you want to record every Chef client run and want to see statistics about successful and failed runs, Chef Reporting is your tool of choice. You can even dive into each individual run across your whole organization if you have Reporting enabled for your Chef clients.

Getting ready

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

Note

Reporting is a premium feature. If you're running your own Chef server you need a Chef Automate license to use it.

Install the reporting knife plugin by running the following command:

mma@laptop:~/chef-repo $ chef gem install knife-reporting
Successfully installed knife-reporting-0.5.0
1 gem installed

How to do it…

Carry out the following steps to see how Reporting tracks your Chef client runs:

  1. Configure Vagrant to send reporting data to your Chef server by editing...

Left arrow icon Right arrow icon

Key benefits

  • Immediately apply Devops techniques and methods, then combine them with powerful Chef tools to manage and automate your infrastructure
  • Address the growing challenges of code management, cloud, and virtualization with Chef quickly
  • Explore and implement the important aspects of Chef Automate using this recipe-based guide

Description

Chef is a configuration management tool that lets you automate your more cumbersome IT infrastructure processes and control a large network of computers (and virtual machines) from one master server. This book will help you solve everyday problems with your IT infrastructure with Chef. It will start with recipes that show you how to effectively manage your infrastructure and solve problems with users, applications, and automation. You will then come across a new testing framework, InSpec, to test any node in your infrastructure. Further on, you will learn to customize plugins and write cross-platform cookbooks depending on the platform. You will also install packages from a third-party repository and learn how to manage users and applications. Toward the end, you will build high-availability services and explore what Habitat is and how you can implement it.

Who is this book for?

This book is for system engineers and administrators who have a fundamental understanding of information management systems and infrastructure. It is also for DevOps Engineers, IT professionals, and organizations who want to automate and gain greater control of their infrastructures with Chef. No experience with Chef is needed, but may help.

What you will learn

  • Test your cookbooks with Test Kitchen
  • Manage cookbook dependencies with Berkshelf
  • Use reporting to keep track of what happens during the execution of chef-client runs across all of the machines
  • Create custom Ohai and Knife plugins
  • Build a high-availability service using Heartbeat
  • Use a HAProxy to load-balance multiple web servers

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 03, 2017
Length: 268 pages
Edition : 3rd
Language : English
ISBN-13 : 9781786465665
Vendor :
Chef
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Feb 03, 2017
Length: 268 pages
Edition : 3rd
Language : English
ISBN-13 : 9781786465665
Vendor :
Chef
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 177.97
Chef Cookbook
$48.99
Mastering Chef Provisioning
$43.99
Chef: Powerful Infrastructure Automation
$84.99
Total $ 177.97 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
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.