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

Arrow left icon
Profile Icon John Arundel
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (16 Ratings)
Paperback Aug 2013 274 pages 2nd Edition
eBook
$19.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon John Arundel
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (16 Ratings)
Paperback Aug 2013 274 pages 2nd Edition
eBook
$19.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$19.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.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

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 : 9781782169765
Vendor :
Puppet
Languages :
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 : Aug 26, 2013
Length: 274 pages
Edition : 2nd
Language : English
ISBN-13 : 9781782169765
Vendor :
Puppet
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 $ 48.99
Puppet 3 Cookbook
$48.99
Total $ 48.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

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.