Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Puppet 3 Cookbook
Puppet 3 Cookbook

Puppet 3 Cookbook: An essential book if you have responsibility for servers. Real-world examples and code will give you Puppet expertise, allowing more control over servers, cloud computing, and desktops. A time-saving, career-enhancing tutorial , Second Edition

eBook
€19.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.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
Table of content icon View table of contents Preview book icon Preview Book

Puppet 3 Cookbook

Chapter 2. Puppet Language and Style

 

Computer language design is just like a stroll in the park. Jurassic Park, that is.

 
 --Larry Wall

In this chapter we will cover:

  • Using community Puppet style

  • Checking your manifests with puppet-lint

  • Using modules

  • Using standard naming conventions

  • Using inline templates

  • Iterating over multiple items

  • Writing powerful conditional statements

  • Using regular expressions in if statements

  • Using selectors and case statements

  • Using the in operator

  • Using regular expression substitutions

Introduction


In this chapter you'll learn to write elegant Puppet manifests. By elegant in this context I mean readable, efficient, and consistent code that conforms to community usage.

We'll look at how to organize and structure your code into modules following community conventions, so that other people will find it easy to read and maintain your code. I'll also show you some powerful features of the Puppet language which will let you write concise, yet expressive, manifests.

Using community Puppet style


If other people need to read or maintain your manifests, or if you want to share code with the community, it's a good idea to follow the existing style conventions as closely as possible. These govern such aspects of your code as layout, spacing, quoting, alignment, and variable references, and the official Puppet Labs recommendations on style are available at

http://docs.puppetlabs.com/guides/style_guide

How to do it…

In this section I'll show you a few of the more important examples and how to make sure that your code is style-compliant.

Indentation

Indent your manifests using two spaces (not tabs), as follows:

node 'monitoring' inherits 'server' {
  include icinga::server
  include repo::apt
}

Quoting

Always quote your resource names, for example:

package { 'exim4':

Not

package { exim4:

Use single quotes for all strings, except when:

  • The string contains variable references (for example, ${name})

  • The string contains character escape sequences (for example, \n)

In these...

Checking your manifests with puppet-lint


The Puppet Labs official style guide outlines a number of style conventions for Puppet code, some of which we've touched on in the preceding section. For example, according to the style guide, manifests:

  • Must use two-space soft tabs

  • Must not use literal tab characters

  • Must not contain trailing white space

  • Should not exceed an 80 character line width

  • Should align parameter arrows (=>) within blocks

Following the style guide will make sure that your Puppet code is easy to read and maintain and, if you're planning to release your code to the public, style compliance is essential. The puppet-lint tool will automatically check your code against the style guide. Here's how to use it:

Getting ready

Here's what you need to do to install puppet-lint:

  1. Run the following command (we'll install puppet-lint as a gem, because that version is much more up-to-date than the APT package available in the Ubuntu Precise repo):

    ubuntu@cookbook:~/puppet$ sudo gem install puppet...

Using modules


One of the most important things you can do to make your Puppet manifests clearer and more maintainable is to organize them into modules.

A module is simply a way of grouping related things: for example, a webserver module might include everything necessary for a machine to be a web server: Apache configuration files, virtual host templates, and the Puppet code necessary to deploy these.

Separating things into modules makes it easier to re-use and share code; it's also the most logical way to organize your manifests. In this example we'll create a module to manage memcached, a memory caching system commonly used with web applications.

How to do it…

Here are the steps to create an example module.

  1. Create the following new directories in your Puppet repo:

    ubuntu@cookbook:~/puppet$ mkdir modules/memcached
    ubuntu@cookbook:~/puppet$ mkdir modules/memcached/manifests
    ubuntu@cookbook:~/puppet$ mkdir modules/memcached/files
    
  2. Create the file modules/memcached/manifests/init.pp with the following...

Using standard naming conventions


Choosing appropriate and informative names for your modules and classes will be a big help when it comes to maintaining your code. This is even truer if other people need to read and work on your manifests.

How to do it…

Here are some tips on how to name things in your manifests:

  1. Name modules after the software or service they manage, for example, apache or haproxy.

  2. Name classes within modules after the function or service they provide to the module, for example, apache::vhosts or rails::dependencies.

  3. If a class within a module disables the service provided by that module, name it disabled. For example, a class which disables Apache should be named apache::disabled.

  4. If a node provides multiple services, have the node definition include one module or class named for each service, for example:

    node 'server014' inherits 'server' {
      include puppet::server
      include mail::server
      include repo::gem
      include repo::apt
      include zabbix
    }
  5. The module that manages users...

Using inline templates


Templates are a powerful way of using embedded Ruby to help build config files dynamically and iterate over arrays, for example. But you can embed Ruby in your manifests directly without having to use a separate file by calling the inline_template function.

How to do it…

Here's an example of using inline_template:

Pass your Ruby code to inline_template within the Puppet manifest, as follows:

cron { 'chkrootkit':
  command => '/usr/sbin/chkrootkit >
    /var/log/chkrootkit.log 2>&1',
  hour    => inline_template('<%= @hostname.sum % 24 %>'),
  minute  => '00',
}

How it works…

Anything inside the string passed to inline_template is executed as if it were an ERB template. That is, anything inside <%= and %> delimiters will be executed as Ruby code, and the rest will be treated as a string.

In this example, we use inline_template to compute a different hour for this cron resource (a scheduled job) for each machine, so that the same job does not...

Iterating over multiple items


Arrays are a powerful feature in Puppet; wherever you want to perform the same operation on a list of things, an array may be able to help. You can create an array just by putting its contents in square brackets:

$lunch = [ 'franks', 'beans', 'mustard' ]

How to do it…

Here's a common example of how arrays are used:

  1. Add the following code to your manifest:

    $packages = [ 'ruby1.8-dev',
                  'ruby1.8',
                  'ri1.8',
                  'rdoc1.8',
                  'irb1.8',
                  'libreadline-ruby1.8',
                  'libruby1.8',
                  'libopenssl-ruby' ]
    
    package { $packages: ensure => installed }
  2. Run Puppet and note that each package should now be installed.

How it works…

Where Puppet encounters an array as the name of a resource, it creates a resource for each element in the array. In the example, a new package resource is created for each of the packages in the $packages array, with the same parameters (ensure => installed). This is a...

Writing powerful conditional statements


Puppet's if statement allows you to change the manifest based on the value of a variable or an expression. With it, you can apply different resources or parameter values depending on certain facts about the node, for example, the operating system, or the memory size. You can also set variables within the manifest which can change the behavior of included classes. For example, nodes in data center A might need to use different DNS servers than nodes in data center B, or you might need to include one set of classes for an Ubuntu system, and a different set for other systems.

How to do it…

Here's an example of a useful conditional statement:

  1. Add the following code to your manifest:

    if $::operatingsystem == 'Ubuntu' {
      notify { 'Running on Ubuntu': }
    } else {
      notify { 'Non-Ubuntu system detected. Please upgrade
        to Ubuntu immediately.': }
    }

How it works…

Puppet treats whatever follows an if keyword as an expression and evaluates it. If the expression evaluates...

Using regular expressions in if statements


Another kind of expression you can test in if statements and other conditionals is the regular expression. A regular expression is a powerful way of comparing strings using pattern matching.

How to do it…

This is one example of using a regular expression in a conditional statement:

  1. Add the following to your manifest:

    if $::lsbdistdescription =~ /LTS/ {
      notify { 'Looks like you are using a Long Term Support
        version of Ubuntu.': }
    } else {
      notify {'You might want to upgrade to a Long Term Support
        version of Ubuntu...': }
    }

How it works…

Puppet treats the text supplied between the forward slashes as a regular expression specifying the text to be matched. If the match succeeds, the if expression will be true and so the code between the first set of curly braces will be executed.

If you wanted instead to do something if the text does not match, use !~ rather than =~:

if $::lsbdistdescription !~ /LTS/ {

There's more…

Regular expressions are very powerful...

Using selectors and case statements


Although you could write any conditional statement using if, Puppet provides a couple of extra forms to help you express conditionals more easily: the selector and the case statement.

How to do it…

Here are some examples of selector and case statements:

  1. Add the following code to your manifest:

    $systemtype = $::operatingsystem ? {
      'Ubuntu' => 'debianlike',
      'Debian' => 'debianlike',
      'RedHat' => 'redhatlike',
      'Fedora' => 'redhatlike',
      'CentOS' => 'redhatlike',
      default  => 'unknown',
    }
    
    notify { "You have a ${systemtype} system": }
  2. Add the following code to your manifest:

    class debianlike {
      notify { 'Special manifest for Debian-like systems': }
    }
    
    class redhatlike {
      notify { 'Special manifest for RedHat-like systems': }
    }
    
    case $::operatingsystem {
      'Ubuntu',
      'Debian': {
        include debianlike
      }
      'RedHat',
      'Fedora',
      'CentOS': {
        include redhatlike
      }
      default: {
        notify { "I don't know what kind of system you have...

Using the in operator


The in operator tests whether one string contains another. Here's an example:

if 'spring' in 'springfield'

The preceding expression is true if the string spring is a substring of springfield, which it is. The in operator can also test for membership of arrays as follows:

if $crewmember in ['Frank', 'Dave', 'HAL' ]

When in is used with a hash, it tests whether the string is a key of the hash:

$interfaces = { 'lo' => '127.0.0.1', 
                'eth0' => '192.168.0.1' }
if 'eth0' in $interfaces {
  notify { "eth0 has address ${interfaces['eth0']}": }
}

How to do it…

The following steps will show you how to use the in operator:

  1. Add the following code to your manifest:

    if $::operatingsystem in [ 'Ubuntu', 'Debian' ] {
      notify { 'Debian-type operating system detected': }
    } elsif $::operatingsystem in [ 'RedHat', 'Fedora', 'SuSE', 'CentOS' ] {
      notify { 'RedHat-type operating system detected': }
    } else {
      notify { 'Some other operating system detected': }
    }
  2. Run Puppet:

    ubuntu...

Using regular expression substitutions


Puppet's regsubst function provides an easy way to manipulate text, search and replace within strings, or extract patterns from strings. We often need to do this with data obtained from a fact, for example, or from external programs.

In this example, we'll see how to use regsubst to extract the first three octets of an IPv4 address (the network part, assuming it's a class C address).

How to do it…

Follow these steps to build the example:

  1. Add the following code to your manifest:

    $class_c = regsubst($::ipaddress, '(.*)\..*', '\1.0')
    notify { "The network part of ${::ipaddress} is
      ${class_c}": }
  2. Run Puppet:

    ubuntu@cookbook:~/puppet$ papply
    Notice: The network part of 10.96.247.132 is 10.96.247.0
    Notice: /Stage[main]/Admin::Test/Notify[The network part of 10.96.247.132 is 10.96.247.0]/message: defined 'message' as 'The 
    etwork part of 10.96.247.132 is 10.96.247.0'
    Notice: Finished catalog run in 0.09 seconds
    

How it works…

regsubst takes at least three parameters...

Left arrow icon Right arrow icon

Key benefits

  • Use Puppet 3 to take control of your servers and desktops, with detailed step-by-step instructions
  • Covers all the popular tools and frameworks used with Puppet: Dashboard, Foreman, and more
  • Teaches you how to extend Puppet with custom functions, types, and providers
  • Packed with tips and inspiring ideas for using Puppet to automate server builds, deployments, and workflows
  •  

Description

A revolution is happening in web operations. Configuration management tools can build servers in seconds, and automate your entire network. Tools like Puppet are essential to taking full advantage of the power of cloud computing, and building reliable, scalable, secure, high-performance systems. More and more systems administration and IT jobs require some knowledge of configuration management, and specifically Puppet."Puppet 3 Cookbook" takes you beyond the basics to explore the full power of Puppet, showing you in detail how to tackle a variety of real-world problems and applications. At every step it shows you exactly what commands you need to type, and includes full code samples for every recipe.The book takes the reader from a basic knowledge of Puppet to a complete and expert understanding of Puppet's latest and most advanced features, community best practices, writing great manifests, scaling and performance, and extending Puppet by adding your own providers and resources. It starts with guidance on how to set up and expand your Puppet infrastructure, then progresses through detailed information on the language and features, external tools, reporting, monitoring, and troubleshooting, and concludes with many specific recipes for managing popular applications.The book includes real examples from production systems and techniques that are in use in some of the world's largest Puppet installations, including a distributed Puppet architecture based on the Git version control system. You'll be introduced to powerful tools that work with Puppet such as Hiera. The book also explains managing Ruby applications and MySQL databases, building web servers, load balancers, high-availability systems with Heartbeat, and many other state-of-the-art techniques

Who is this book for?

"Puppet 3 Cookbook" is for anyone who builds and administers servers, especially in a web operations context. It requires some experience of Linux systems administration, including familiarity with the command line, file system, and text editing. No programming experience is required.

What you will learn

  • Installing and setting up Puppet for the first time
  • Producing eye-catching reports and information for management
  • Understanding common error messages and troubleshooting common problems
  • Managing large networks
  • Taking control of configuration data with Hiera and encrypting secrets with GnuPG
  • Producing reliable, clean, maintainable code to community standards with puppet-lint and rspec-puppet
  • Using classes and inheritance to write powerful Puppet code
  • Deploying configuration files and templates for lightning-fast installations
  • Using virtual machines to build test and staging environments, and production systems on cloud platforms such as EC2
  • Automating every aspect of your systems including provisioning, deployment and change management
  • Making Puppet reliable, performant, and scalable

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 26, 2013
Length: 274 pages
Edition : 2nd
Language : English
ISBN-13 : 9781782169512
Vendor :
Puppet
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

Product Details

Publication date : Aug 26, 2013
Length: 274 pages
Edition : 2nd
Language : English
ISBN-13 : 9781782169512
Vendor :
Puppet
Languages :
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 37.99
Puppet 3 Cookbook
€37.99
Total 37.99 Stars icon

Table of Contents

9 Chapters
Puppet Infrastructure Chevron down icon Chevron up icon
Puppet Language and Style Chevron down icon Chevron up icon
Writing Better Manifests Chevron down icon Chevron up icon
Working with Files and Packages Chevron down icon Chevron up icon
Users and Virtual Resources Chevron down icon Chevron up icon
Applications Chevron down icon Chevron up icon
Servers and Cloud Infrastructure Chevron down icon Chevron up icon
External Tools and the Puppet Ecosystem Chevron down icon Chevron up icon
Monitoring, Reporting, and Troubleshooting Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(16 Ratings)
5 star 50%
4 star 31.3%
3 star 6.3%
2 star 12.5%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Alon Becker Feb 09, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I wanted to enhance my Puppet knowledge and this book does just that. From using tags to encrypting sensitive data or with HieraGPG or creating your own custom function this book covers a tremendous amount of material. The book covers masterless puppet installation and really covers the topic well. It goes in to detail of how to set up a masterless ecosystem with Rake, Puppet and Git. My only complaints about this book is it does not cover enough of when to use masterless Puppet or when to have a Puppet master. Thus it does not cover PuppetDB, which is something we use. All in all a great book.I learned a lot from this book and have a bunch of new tools to use in my day to day use of Puppet.
Amazon Verified review Amazon
Stephen Collier Mar 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book to learn puppet easy to read, well written. Has helped me understand how and why puppet works.
Amazon Verified review Amazon
ad_amazon Dec 07, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Wer schon ein paar Grundlagen hat, kann in dem Buch viele interessante Beispiele finden.Ich schaue immer mal wieder in das Buch.
Amazon Verified review Amazon
Thomas Dao Jan 04, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is very well-structured for the beginner to intermediate puppet and devops person.Starts off with overview and goes thru step by step examples and problems with helpfulalong the way. Using this book was able to setup and create recipes at the workplace. Got the PDFversion and read it both on my iPad and Android tablet.[...]
Amazon Verified review Amazon
carl Dec 02, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
John Arundel wrote another book - Puppet 2.7 cookbook in 2011. You can consider this one is the revised version with additional puppet 3 features added. Through this book, John shared his hands-on puppet development experience and gave his approach to deploy puppet infrastructure in distributed environment. Although each environment differs, reader will be able to get some idea from the usage described in book and apply the guideline within their own infrastructure.Many people like me, we are not coding puppet every day. Instead we build the framework, we developed module to meet business request. Then we move on to the next task. We don't spend lots of time to tune our code for best efficiency, nor we study public module to learn tricks/patterns on daily basis. This book happens to be a good resource for such readers and it uses many user cases to demonstrate what is the most efficient way.Author is not trying to cover every aspect in a less than 300 pages book. This book is more or less the summary of author's puppet working experience. He tried to list the most important concepts/features, wished readers can benefit from them and can have a more advanced start line.I definitely recommend this book to people who start programming puppet and developers, who are doing intermittent puppet development.
Amazon Verified review Amazon
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.