0% found this document useful (0 votes)
482 views325 pages

Puppet Reference 3 6 PDF

Getting Around This manual is split into several sections, which can be reached from the left sidebar. The Puppet 3. Release Notes contain information about puppet 3.6's new features. "Modules" explains how to organize your puppet manifests, obtain pre-existing modules.

Uploaded by

Vagner Kaelher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
482 views325 pages

Puppet Reference 3 6 PDF

Getting Around This manual is split into several sections, which can be reached from the left sidebar. The Puppet 3. Release Notes contain information about puppet 3.6's new features. "Modules" explains how to organize your puppet manifests, obtain pre-existing modules.

Uploaded by

Vagner Kaelher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 325

Puppet 3.

6 Reference Manual
(Generated on June 24, 2014, from git revision 59e2e89afc535d8d65807a548f39836e038e65a2)
Puppet 3.6 Reference Manual
Welcome to the Puppet 3.6 Reference Manual! Use the navigation to the left to get around.
Previous Versions
Puppet 3.5
Puppet 3.0 through 3.4
Puppet 2.7
Getting Started
To install Puppet 3.6, see the Puppet installation guide. For general advice on upgrading between
major versions, see Upgrading Puppet.
Getting Around
This manual is split into several sections, which can be reached from the left sidebar. A few notable
pages:
The Puppet 3.6 Release Notes contain information about Puppet 3.6s new features, and tracks
changes from patch releases.
The Resource Type Reference is the page where experienced Puppet users spend most of their
time.
Puppet uses its own conguration language. The Language Summary gives some context and
acts as a starting point for the language reference.
The Visual Index to the Puppet Language can help you nd the reference for a piece of syntax
when you know what it looks like but dont know what its called.
Modules explains how to organize your Puppet manifests, obtain pre-existing modules, and
publish your own modules for public use.
Puppet 3.6 Release Notes
This page tells the history of the Puppet 3.6 series. (Elsewhere: release notes for Puppet 3.0 3.4
and Puppet 3.5.)
Puppets version numbers use the format X.Y.Z, where:
X must increase for major backwards-incompatible changes
Y may increase for backwards-compatible new functionality
Z may increase for bug xes
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 2/325
How to Upgrade
If youre upgrading from a 3.x version of Puppet, you can usually just go for it. Upgrade your
puppet master servers before upgrading the agents they serve. (But do look at the table of contents
above and see if there are any Upgrade Warning notes for the new version.)
If youre upgrading from Puppet 2.x, please learn about major upgrades of Puppet rst!We have
important advice about upgrade plans and package management practices. The short version is:
test rst, roll out in stages, give yourself plenty of time to work with. Also, read the release notes for
Puppet 3 for a list of all the breaking changes made between the 2.x and 3.x series.
Puppet 3.6.2
Released June 10, 2014.
Puppet 3.6.2 is a security and bug x release in the Puppet 3.6 series. It addresses two security
vulnerabilities and includes xes for a number of fairly recent bugs. It also introduces a new
disable_warnings setting to squelch deprecation messages.
Security Fixes
CVE-2014-3248 (AN ATTACKER COULD CONVINCE AN ADMINISTRATOR TO UNKNOWINGLY EXECUTE
MALICIOUS CODE ON PLATFORMS WITH RUBY 1.9.1 AND EARLIER)
On platforms running Ruby 1.9.1 and earlier, previous code would load Ruby source les from the
current working directory. This could lead to the execution of arbitrary code during puppet runs.
CVE-2014-3253 (APACHE 2.4+ DOES NOT ENFORCE CRL CHECKS BY DEFAULT)
Apache 2.4+ uses the SSLCARevocationCheck setting to determine how to check the certicate
revocation list (CRL) when establishing a connection. Unfortunately, the default setting is none, so a
puppet master running Apache 2.4+ and Passenger will ignore the CRL by default. This release
updates the Apache vhost settings to enable CRL checking.
Feature: Disabling Deprecation Warnings
Puppet 3.6.0 deprecated cong-le environments, leading to warnings during every puppet run for
people who havent yet switched to the new and improved directory environments. The high volume
of duplicate deprecation warnings was deemed annoying enough that weve added a new feature to
allow people to disable them.
You can now use the new (optional) disable_warnings setting in puppet.conf or on the command
line to suppress certain types of warnings. For now, disable_warnings can only be set to
deprecations, but other warning types may be added in future versions. All warnings are still
enabled by default.
Related issue:
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 3/325
PUP-2650: 3.6.1 issues warning message for deprecation
Fix for Directory Environments Under Webrick
Puppet 3.6.1 introduced a bug that prevented directory environments from functioning correctly
under Webrick, causing this error: Attempted to pop, but already at root of the context stack. This
release xes the bug.
Related issue:
PUP-2659: Puppet stops working with error Attempted to pop, but already at root of the context
stack.
Fixes to purge_ssh_keys
Two bugs were discovered with the new (as of 3.6.0) purge_ssh_keys attribute for the user type.
These bugs could prevent SSH keys from being purged under certain circumstances, and have been
xed.
Related issues:
PUP-2635: user purge_ssh_keys not purged
PUP-2660: purging ssh_authorized_key fails because of missing user value
Default environment_timeout increased
The previous default value for environment_timeout was 5s, which turns out to be way too short
for a typical production environment. This release changes the default environment_timeout to
3m.
Related issue:
PUP-2639: Increase environment_timeout default.
General Bug Fixes
PUP-2689: A node cant always collect its own exported resources
PUP-2692: Puppet master passenger processes keep growing
PUP-2705: Regression with external facts pluginsync not preserving executable bit
Puppet 3.6.1
Released May 22, 2014.
Puppet 3.6.1 is a bug x release in the Puppet 3.6 series. It also makes the transaction_uuid more
reliably available to extensions.
Changes to RPM Behavior With Virtual Packages
In Puppet 3.5, the RPM package provider gained support for virtual packages. (That is, Puppet
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 4/325
would handle package names the same way Yum does.) In this release, we added a new
allow_virtual attribute for package, which defaults to false. Youll have to set it to true to
manage virtual packages.
We did this because there are a few cases where a virtual package name can conict with a non-
virtual package name, and Puppet will manage the wrong thing. (Again, just like Yum would.) For
example, if you set ensure => absent on the inetd package, Puppet might uninstall the xinetd
package, since it provides the inetd virtual package.
We had to treat that change as a regression, so were currently defaulting allow_virtual => false
to preserve compatibility in the Puppet 3 series. The default will change to true for Puppet 4. If you
manage any packages with virtual/non-virtual name conicts, you should set allow_virtual =>
false on a per-resource basis.
If you dont have any resources with ambiguous virtual/non-virtual package names, you can enable
the Puppet 4 behavior today by setting a resource default in the main manifest:
Package {
allow_virtual => true,
}
PUP-2182: Package resource not working as expected in 3.5.0
Improvements to transaction_uuid in Reports and Node Termini
Each catalog request from an agent node has a unique identier, which persists through the entire
run and ends up in the report. However, it was being omitted from reports when the catalog run
failed, and node termini had no access to it. This release adds it to failed reports and node object
requests.
(Note that transaction_uuid isnt available in the standard ENC interface, but it is available to
custom node termini.)
PUP-2522: The transaction_uuid should be available to a node terminus
PUP-2508: Failed compilation does not populate environment, transaction_uuid in report
Windows Start Menu Fixes
If your Windows machine only had .NET 4.0 or higher, the Run Facter and Run Puppet Agent
start menu items wouldnt work, stating that they needed an older version of .NET installed. This is
now xed.
PUP-1951: Unable to Run Facter or Run Puppet Agent from Start Menu on Windows 8/2012 -
Requires .NET Framework 3.5 installed
Improved Passenger Packages on Debian/Ubuntu
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 5/325
The Apache vhost cong we ship in the Debian/Ubuntu puppetmaster-passenger package had
some non-optimal TLS settings. This has been improved.
PUP-2582: Enable TLSv1.2 in apache vhost cong
HTTP API Fixes
A regression in Puppet 3.5 broke DELETE requests to Puppets HTTP API. Also, a change in 3.6.0
made puppet agent log spurious warnings when using multiple values for the source attribute.
These bugs are both xed.
PUP-2505: REST API regression in DELETE request handling
PUP-2584: Spurious warnings when using multiple le sources(regression in 3.6.0)
Directory Environment Fixes
If puppet master was running under Rack (e.g. with Passenger) and the environmentpath was
congured in the [master] section of puppet.conf (instead of in [main]), Puppet would use the
wrong set of environments. This has been xed.
PUP-2607: environmentpath does not work in master section of cong
PUP-2610: Rack masters lose track of environment loaders
Future Parser Improvements
This release xes two compatibility bugs where the future parser conicted with the 3.x parser. It
also xes a bug with the new EPP templating language.
PUP-1894: Cannot render EPP templates from a module
PUP-2568: Cannot use class references with upper cased strings
PUP-2581: Interpolated variables with leading underscore regression (regression in 3.5.1)
Puppet 3.6.0
Released May 15, 2014. (RC1: May 6.)
Puppet 3.6.0 is a backward-compatible features and xes release in the Puppet 3 series. The
biggest things in this release are:
Improvements to directory environments, and the deprecation of cong le environments
Support for purging unmanaged ssh_authorized_key resources
Support for installing gems for a custom provider as part of a Puppet run
A congurable global logging level
A congurable hashing algorithm (for FIPS compliance and other purposes)
Improvements to the experimental future parser
Improvements for Directory Environments
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 6/325
Directory environments were introduced in Puppet 3.5 as a partially nished (but good enough for
most people) feature. With Puppet 3.6, we consider them completed. Were pretty sure they can now
handle every use case for environments weve ever heard of.
The nal piece is the environment.conf le. This optional le allows any environment to override
the manifest, modulepath, and config_version settings, which is necessary for some people and
wasnt possible in Puppet 3.5. You can now exclude global module directories for some
environments, or point all environments at a global main manifest le. For details, see the page on
directory environments and the page on environment.conf.
Its also now possible to tune the cache timeout for environments, to improve performance on your
puppet master. See the note on timeout tuning in the directory environments page.
PUP-1114: Deprecate environment conguration in puppet.conf
PUP-2213: The environmentpath setting is ignored by puppet faces unless set in [main]
PUP-2215: An existing directory environment will use cong_version from an underlying legacy
environment of the same name.
PUP-2290: ca_server and directory based environments dont play nice together
PUP-1596: Make modulepath, manifest, and cong_version congurable per-environment
PUP-1699: Cache environments
PUP-1433: Deprecate implicit environment settings and update packaging
Deprecation: Cong-File Environments and the Global manifest/modulepath/config_version
Settings
Now that directory environments are completed, cong-le environmentsare deprecated. Dening
environment blocks in puppet.conf will cause a deprecation warning, as will any use of the
modulepath, manifest, and config_version settings in puppet.conf.
This also means that using no environments is deprecated. In a future version of Puppet (probably
Puppet 4), directory environments will always be enabled, and the default production environment
will take the place of the global manifest/modulepath/config_version settings.
Related issues:
PUP-1114: Deprecate environment conguration in puppet.conf
PUP-1433: Deprecate implicit environment settings and update packaging
Feature: Purging Unmanaged SSH Authorized Keys
Purging unmanaged ssh_authorized_key resources has been on the most-wanted features list for
a very long time, and we havent been able to make the resources meta-type accommodate it.
Fortunately, the user type accommodates it very nicely. You can now purge unmanaged SSH keys
for a user by setting the purge_ssh_keys attribute:
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 7/325
user { 'nick':
ensure => present,
purge_ssh_keys => true,
}
This will purge any keys in ~nick/.ssh/authorized_keys that arent being managed as Puppet
resources.
Related issues:
PUP-1174: PR (2247) Ability to purge .ssh/authorized_keys
PUP-1955: purge_ssh_keys causes stack trace when creating new users on redhat
Feature: Installing Gems for a Custom Provider During Puppet Runs
Previously, custom providers that required one or more gems would fail if at least one gem was
missing before the current puppet run, even if they had been installed by the time the provider was
actually called. This release xes the behavior so that custom providers can rely on gems installed
during the same puppet run.
Related issue:
PUP-1879: Library load tests in features should clear rubygems path cache
Feature: Global log_level Setting
You can now set the global log level using the log_level setting in puppet.conf. It defaults to
notice, and can be set to debug, info, notice, warning, err, alert, emerg, or crit.
Related issue:
PUP-1854: Global log_level param
Feature: digest_algorithm Setting
You can now change the hashing algorithm that puppet uses for le digests to sha256 using the
new digest_algorithm setting in puppet.conf. This is especially important for FIPS-compliant
hosts, which would previously crash when puppet tried to use MD5 for hashing. Changing this
setting wont aect the md5 or fqdn_rand functions.
This setting must be set to the same value on all agents and all masters simultaneously; if they
mismatch, youll run into two problems:
PUP-2427: Pluginsync will download every le every time if digest_algorithms do not agree All
les with a source attribute will download on every run, which wastes a lot of time and can
swamp your puppet master.
PUP-2423: Filebucket server should warn, not fail, if checksum type is not supported If youre
using a remote lebucket to back up le content, agent runs will fail.
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 8/325
Related issue:
PUP-1840: Let user change hashing algorithm, to avoid crashing on FIPS-compliant hosts
Improvements to the Future Parser
Its still experimental, but the future parser has gotten a lot of attention in this release. For
example, functions can now accept lambdas as arguments using the new Callable type. There are
also a few changes laying the groundwork for the upcoming catalog builder.
PUP-1960: realizing an empty array of resources fails in future evaluator
PUP-1964: Using undened variable as class parameter default fails in future evaluator
PUP-2190: Accessing resource metaparameters fails in future evaluator
PUP-2317: Future parser does not error on import statements
PUP-2302: New evaluator does not properly handle resource defaults
PUP-2026: Add a LambdaType to the type system
PUP-2027: Add support for Lambda in Function Call API
PUP-1956: Add function loader for new function API
PUP-2344: Functions unable to call functions in dierent modules
PUP-485: Add assert_type functions for type checks
PUP-1799: New Function API
PUP-2035: Implement Loader infrastructure API
PUP-2241: Add logging functions to static loader
PUP-485: Add assert_type functions for type checks
PUP-1799: New Function API
PUP-2035: Implement Loader infrastructure API
PUP-2241: Add logging functions to static loader
OS Support Changes
This release improves compatibility with Solaris 10 and adds support for Ubuntu 14.04 (Trusty
Tahr).
Support for Ubuntu 13.04 (Raring Ringtail) has been discontinued; it was EOLd in January 2014.
Related issues:
PUP-1749: Puppet module tool does not work on Solaris
PUP-2100: Allow Inheritance when setting Deny ACEs
PUP-1711: Add Ubuntu 14.04 packages
PUP-1712: Add Ubuntu 14.04 to acceptance
PUP-2347: Remove raring from build_defaults, it is EOL
PUP-2418: Remove Tar::Solaris from module_tool
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 9/325
Module Tool Changes
The puppet module tool has been updated to deprecate the Modulele in favor of metadata.json.
To help ease the transition, the module tool will automatically generate metadata.json based on a
Modulele if it nds one. If neither Modulele nor metadata.json is available, it will kick o an
interview and generate metadata.json based on your responses.
The new module template has also been updated to include a basic README and spec tests. For
more information, see Publishing Modules on the Puppet Forge.
Related issues:
PUP-1976: puppet module build should use metadata.json as input format
PUP-1977: puppet module build should create metadata.json instead of Modulefile
PUP-2045: puppet module generate should produce a skeleton Rakele
PUP-2093: PMT should use the Forges /v3 API
PUP-2284: Add a user interview for creating a metadata.json le
PUP-2285: Update PMT generates README template
Issues xed during RC:
PUP-2484: puppet module build should provide deprecated functionality with warning until
Puppet v4 this would cause the Modulele to be ignored if a metadata.json le also existed.
PUP-2561: PMT may deadlock when packing or unpacking large tarballs
PUP-2562: PMT will not install puppetlabs/openstack 4.0.0
Type and Provider Fixes
PACKAGE:
Several providers were updated to support the install_options attribute, and the yum provider
now has special behavior to make --enablerepo and --disablerepo work well when you set them
as install_options.
PUP-748: PR (2067): Zypper provider install options - darix
PUP-620: (PR 2429) Add install_options to gem provider
PUP-1769: PR (2414) yum provider to support install_options
PUP-772: PR (2082): Add install options to apt
PUP-1060: enablerepo and disablerepo for yum type
NAGIOS:
PUP-1041: PR (2385) naginator not parsing blank parameters
CRON:
PUP-1585: PR (2342) cron resources with target specied generate duplicate entries
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 10/325
PUP-1586: PR (2331) Cron Type sanity check for the command parameter is broken
PUP-1624: PR (2342) Cron handles crontabs equality of target and user strangely
SERVICE:
OpenBSD services can now be enabled and disabled, and we xed some bugs on other platforms.
PUP-1751: PR (2383): Suse chkcong check boot.<service> always returns 1 whether the
service is enabled/disabled. - m4ce
PUP-1932: systemd reports transient (in-memory) services
PUP-1938: Remove Ubuntu default from Debian service provider
PUP-1332: puppet resource service fails on Ubuntu 13.04 and higher
PUP-2143: Allow OpenBSD service provider to implement :enableable
FILE:
We xed a regression from Puppet 3.0 that broke le resources whose source URL specied a
server other than the default. (That is, puppet://myserver/modules/... instead of
puppet:///modules/....)
PUP-1892: PR (2420) Puppet remote leserver facility for le resources.
YUMREPO:
We xed a few lingering regressions from the big yumrepo cleanup of Puppet 3.5, and added
support for the skip_if_unavailable parameter.
PUP-2218: yumrepo can no longer manage repositories in yum.conf
PUP-2291: yumrepo priority can not be sent to absent
PUP-2292: Insucient tests on yumrepos => absent
PUP-2279: Add support for skip_if_unavailable parameter to yumrepo
AUGEAS:
We added better control over the way Augeas resources display dis, for better security and less
noise.
PUP-2033: Allow augeas dis to respect loglevel
PUP-2048: Allow suppressing dis on augeas
General Bug Fixes
PUP-530: Installer for Puppet 3 does not check for hiera
PUP-1547: PR (2311) Undened method `groups for nil:NilClass
PUP-1552: V2.0 API reports Not Authorized as a RUNTIME_ERROR
PUP-1924: source function library before client syscong overrides
PUP-1954: use of attr causes deprecation warning
PUP-1986: Permissions for libdir are set arbitrarily
Puppet 3.6 Reference Manual Puppet 3.6 Reference Manual 11/325
PUP-2073: PR (2477) Multiple values for di_args causes di execution failure
PUP-2278: puppet module install fails when given path containing spaces
PUP-2101: resource parser: add the resource name on the validation error message when using
create_resources
PUP-2282: Deprecation warnings issued with dierent messages from the same line are
suppressed.
PUP-2306: Puppet::Util::Execution.execute no longer returns a String
PUP-2415: Puppet Agent Service - Rename /etc/syscong/puppetagent to
/etc/syscong/puppet
PUP-2416: Puppet Service - Use no-daemonize and no forking (Master and Agent)
PUP-2417: Puppet Agent Should wait for Puppet Master to nish starting, if puppet master is
installed
PUP-2395: Installation problem for puppetmaster-puppet 3.5.1 on Ubuntu 13.10
All Resolved Issues for 3.6.0
Our ticket tracker has the list of all issues resolved in Puppet 3.6.0.
Puppet 3.6 System Requirements
Hardware
The puppet agent service has no particular hardware requirements and can run on nearly anything.
However, the puppet master service is fairly resource intensive, and should be installed on a robust
dedicated server.
At minimum, your puppet master server should have two processor cores and at least 1 GB RAM.
To comfortably serve at least 1000 nodes, it should have 2-4 processor cores and at least 4 GB
RAM.
The demands on the puppet master will vary widely between dierent deployments. The total needs
are aected by the number of agents being served, how frequently those agents check in, how
many resources are being managed on each agent, and the complexity of the manifests and
modules in use.
Platforms With Packages
Puppet 3.6 and all of its prerequisites will run on the following platforms, and Puppet Labs provides
ocial packages in our package repositories.
To install Puppet 3.6, see the Puppet installation guide.
Puppet 3.6 Reference Manual Puppet 3.6 System Requirements 12/325
Red Hat Enterprise Linux (and Derivatives)
We publish ocial packages and run automated testing on the following versions:
Enterprise Linux 5 (also supported by Puppet Enterprise)
Enterprise Linux 6 (also supported by Puppet Enterprise)
Enterprise Linux 7
Puppet Enterprise also supports RHEL 4, which does not receive packages for open source Puppet.
(Note that RHEL 5 requires an updated Ruby 1.8.7 from our yum repo.)
This information applies to RHEL itself, as well as any distributions that maintain binary
compatibility with it, including but not limited to CentOS, Scientic Linux, Oracle Linux, and
Ascendos.
Debian and Ubuntu
We publish ocial packages and run automated testing on the following versions:
Debian 6 Squeeze (obsolete stable release) (also supported by Puppet Enterprise)
Debian 7 Wheezy (current stable release) (also supported by Puppet Enterprise)
Ubuntu 14.04 LTS Trusty Tahr
Ubuntu 12.04 LTS Precise Pangolin (also supported by Puppet Enterprise)
Ubuntu 10.04 LTS Lucid Lynx (also supported by Puppet Enterprise)
We publish packages for the following versions, but do not run automated testing on them:
Ubuntu 13.10 Saucy Salamander
Fedora
We publish ocial packages and run automated testing on the following versions:
Fedora 19
Fedora 20
Windows
We publish ocial packages and run automated testing on the following versions:
Windows Server 2012 and 2012 R2 (also supported by Puppet Enterprise)
Windows Server 2008 R2 (also supported by Puppet Enterprise)
Windows Server 2003 R2 (also supported by Puppet Enterprise)
We publish packages for the following versions, but do not run automated testing on them:
Windows Server 2008 (also supported by Puppet Enterprise)
Puppet 3.6 Reference Manual Puppet 3.6 System Requirements 13/325
Windows Server 2003 (also supported by Puppet Enterprise)
Windows 7 and 8 (also supported by Puppet Enterprise)
Windows Vista
Mac OS X
Although we publish packages for Mac OS X, we do not run automated testing on it.
Mac OS X, version 10.9 (Mavericks) and higher
Platforms Without Packages
Puppet and its prerequisites are known to run on the following platforms, but we do not provide
ocial packages and do not perform automated testing.
Other Linux
SUSE Linux Enterprise Server, version 11 and higher
Gentoo Linux
Mandriva Corporate Server 4
ArchLinux
Other Unix
Oracle Solaris, version 10 and higher (Puppet Labs performs limited automated testing on Solaris
11.)
AIX, version 5.3 and higher
FreeBSD 4.7 and later
OpenBSD 4.1 and later
HP-UX
Basic Requirements
If youre installing Puppet via the ocial packages, you wont need to worry about these
prerequisites; your systems package manager will handle all of them. These are only listed for
those running Puppet from source or on unsupported systems.
Puppet 3.6 has the following prerequisites:
Ruby
Use one of the following versions of MRI (standard) Ruby:
2.1.x Note: We run spec tests for Ruby 2.1, but since none of our tested platforms ship with it
yet, we dont run acceptance tests on it. This means we think its good, but it might have
problems we dont know about yet.
2.0.x
Puppet 3.6 Reference Manual Puppet 3.6 System Requirements 14/325
1.9.3
1.8.7
Other interpreters and versions of Ruby are not covered by our tests, and may or may not work.
Mandatory Libraries
Facter 1.7.0 or later
Hiera 1.0 or later
The json gem (any modern version).
Optional Libraries
The rgen gem version 0.6.1 or later is required when using Puppet with parser = future
enabled.
The msgpack gem is required if you are using msgpack serialization.
Language: Visual Index
This page can help you nd syntax elements when you cant remember their names.
file {'ntp.conf':
path => '/etc/ntp.conf',
ensure => file,
content => template('ntp/ntp.conf'),
owner => root,
mode => 0644,
}
A resource declaration.
file: The resource type
ntp.conf: The title
path: An attribute
'/etc/ntp.conf': A value; in this case, a string
template('ntp/ntp.conf'): A function call that returns a value; in this case, the template
function, with the name of a template in a module as its argument
package {'ntp':
ensure => installed,
before => File['ntp.conf'],
}
service {'ntpd':
ensure => running,
Puppet 3.6 Reference Manual Language: Visual Index 15/325
subscribe => File['ntp.conf'],
}
Two resources using the before and subscribe relationship metaparameters (which accept
resource references).
Package['ntp'] -> File['ntp.conf'] ~> Service['ntpd']
Chaining arrows forming relationships between three resources, using resource references.
$package_list = ['ntp', 'apache2', 'vim-nox', 'wget']
A variable being assigned an array value.
$myhash = { key => { subkey => 'b' }}
A variable being assigned a hash value.
...
content => "Managed by puppet master version ${serverversion}"
A master-provided built-in variable being interpolated into a double-quoted string (with optional
curly braces).
class ntp {
package {'ntp':
...
}
...
}
A class denition, which makes a class avaliable for later use.
include ntp
require ntp
class {'ntp':}
Declaring a class in three dierent ways: with the include function, with the require function,
and with the resource-like syntax. Declaring a class causes the resources in it to be managed.
define apache::vhost ($port, $docroot, $servername = $title, $vhost_name =
'*') {
Puppet 3.6 Reference Manual Language: Visual Index 16/325
include apache
include apache::params
$vhost_dir = $apache::params::vhost_dir
file { "${vhost_dir}/${servername}.conf":
content => template('apache/vhost-default.conf.erb'),
owner => 'www',
group => 'www',
mode => '644',
require => Package['httpd'],
notify => Service['httpd'],
}
}
A dened type, which makes a new resource type available. Note that the name of the type has
two namespace segments.
apache::vhost {'homepages':
port => 8081,
docroot => '/var/www-testhost',
}
Declaring a dened resource(or instance) of the type dened above.
Apache::Vhost['homepages']
A resource reference to the dened resource declared above. Note that every namespace segment
must be capitalized.
node 'www1.example.com' {
include common
include apache
include squid
}
A node denition.
node /^www\d+$/ {
include common
}
A regular expression node denition.
import nodes/*.pp
An import statement. Should be avoided in all but a few circumstances.
Puppet 3.6 Reference Manual Language: Visual Index 17/325
# comment
/* comment */
Two comments.
if $is_virtual == 'true' {
warn( 'Tried to include class ntp on virtual machine; this node may be
misclassified.' )
}
elsif $operatingsystem == 'Darwin' {
warn ( 'This NTP module does not yet work on our Mac laptops.' )
else {
include ntp
}
An if statement, whose conditions are expressions that use agent-provided facts.
if $hostname =~ /^www(\d+)\./ {
notify { "Welcome web server #$1": }
}
An if statement using a regular expression and the regex match operator.
if 'www' in $hostname {
...
}
An if statement using an in expression
case $operatingsystem {
'Solaris': { include role::solaris }
'RedHat', 'CentOS': { include role::redhat }
/^(Debian|Ubuntu)$/:{ include role::debian }
default: { include role::generic }
}
A case statement.
$rootgroup = $osfamily ? {
'Solaris' => 'wheel',
/(Darwin|FreeBSD)/ => 'wheel',
default => 'root',
}
A selector statement being used to set the value of the $rootgroup variable.
Puppet 3.6 Reference Manual Language: Visual Index 18/325
User <| groups == 'admin' |>
A resource collector, sometimes called the spaceship operator.
Concat::Fragment <<| tag == "bacula-storage-dir-${bacula_director}" |>>
An exported resource collector, which works with exported resources
Exec {
path => '/usr/bin:/bin:/usr/sbin:/sbin',
environment => 'RUBYLIB=/opt/puppet/lib/ruby/site_ruby/1.8/',
logoutput => true,
timeout => 180,
}
A resource default for resources of the exec type.
Exec['update_migrations'] {
environment => 'RUBYLIB=/usr/lib/ruby/site_ruby/1.8/',
}
A resource override, which will only work in an inherited class.
Exec <| title == 'update_migrations' |> {
environment => 'RUBYLIB=/usr/lib/ruby/site_ruby/1.8/',
}
A resource override using a collector, which will work anywhere. Dangerous, but very useful in
rare cases.
@user {'deploy':
uid => 2004,
comment => 'Deployment User',
group => www-data,
groups => ["enterprise"],
tag => [deploy, web],
}
A virtual resource.
@@nagios_service { "check_zfs${hostname}":
use => 'generic-service',
host_name => "$fqdn",
Puppet 3.6 Reference Manual Language: Visual Index 19/325
check_command => 'check_nrpe_1arg!check_zfs',
service_description => "check_zfs${hostname}",
target => '/etc/nagios3/conf.d/nagios_service.cfg',
notify => Service[$nagios::params::nagios_service],
}
An exported resource declaration.
Language: Basics
Puppet uses its own conguration language, which was designed to be accessible to sysadmins.
The Puppet language does not require much formal programming experience and its syntax was
inspired by the Nagios conguration le format.
Resources, Classes, and Nodes
The core of the Puppet language is declaring resources. Every other part of the language exists to
add exibility and convenience to the way resources are declared.
Groups of resources can be organized into classes, which are larger units of conguration. While a
resource may describe a single le or package, a class may describe everything needed to congure
an entire service or application (including any number of packages, cong les, service daemons,
and maintenance tasks). Smaller classes can then be combined into larger classes which describe
entire custom system roles, such as database server or web application worker.
Nodes that serve dierent roles will generally get dierent sets of classes. The task of conguring
which classes will be applied to a given node is called node classication.Nodes can be classied in
the Puppet language using node denitions; they can also be classied using node-specic data
from outside your manifests, such as that from an ENC or Hiera.
Ordering
Puppets language is mostly declarative: Rather than listing a series of steps to carry out, a Puppet
manifest describes a desired nal state.
The resources in a manifest can be freely ordered they will not necessarily be applied to the
system in the order they are written. This is because Puppet assumes most resources arent related
to each other. If one resource depends on another, you must say so explicitly. (If you want a short
section of code to get applied in the order written, you can use chaining arrows.)
To see how the Puppet languages features have evolved over time, see History of the Puppet
Language.
Puppet 3.6 Reference Manual Language: Basics 20/325
Although resources can be freely ordered, several parts of the language do depend on parse order.
The most notable of these are variables, which must be set before they are referenced.
Congurable Ordering
The ordering setting allows you to congure how resources are ordered when relationships are not
present.
By default, the order of unrelated resources is eectively random. If you set ordering = manifest
in puppet.conf, Puppet will apply unrelated resources in the order in which they appear in the
manifest.
This setting only aects resources whose relative order is not otherwise determined, e.g., by
metaparameters like before or require. See the language page on relationships for more
information.
Files
Puppet language les are called manifests, and are named with the .pp le extension. Manifest
les:
Should use UTF8 encoding
May use Unix (LF) or Windows (CRLF) line breaks (note that the line break format also aects
literal line breaks in strings)
Puppet always begins compiling with a single manifest (which may be broken up into several
pieces), called the site manifest or main manifest. See the reference page on the main manifest
for details about this special le/directory.
Any classes declared in the main manifest can be autoloaded from manifest les in modules.
Puppet will also autoload any classes declared by an optional external node classier. See the
reference page on catalog compilation for details.
The simplest Puppet deployment is a lone main manifest le with a few resources. Complexity can
grow progressively, by grouping resources into modules and classifying your nodes more
granularly.
Compilation and Catalogs
Puppet manifests can use conditional logic to describe many nodes congurations at once. Before
conguring a node, Puppet compiles manifests into a catalog, which is only valid for a single node
and which contains no ambiguous logic.
Catalogs are static documents which contain resources and relationships. At various stages of a
Puppet run, a catalog will be in memory as a Ruby object, transmitted as JSON, and persisted to disk
as YAML. The catalog format used by this version of Puppet is not documented and does not have a
Puppet 3.6 Reference Manual Language: Basics 21/325
spec.
In the standard agent/master architecture, nodes request catalogs from a puppet master server,
which compiles and serves them to nodes as needed. When running Puppet standalone with puppet
apply, catalogs are compiled locally and applied immediately.
Agent nodes cache their most recent catalog. If they request a catalog and the master fails to
compile one, they will re-use their cached catalog. This recovery behavior is governed by the
usecacheonfailure setting in puppet.conf. When testing updated manifests, you can save time by
turning it o.
For more information, see the reference page on catalog compilation.
Example
The following short manifest manages NTP. It uses package, le, and service resources; a case
statement based on a fact; variables; ordering and noticationrelationships; and le contents being
served from a module.
case $operatingsystem {
centos, redhat: { $service_name = 'ntpd' }
debian, ubuntu: { $service_name = 'ntp' }
}
package { 'ntp':
ensure => installed,
}
service { 'ntp':
name => $service_name,
ensure => running,
enable => true,
subscribe => File['ntp.conf'],
}
file { 'ntp.conf':
path => '/etc/ntp.conf',
ensure => file,
require => Package['ntp'],
source => "puppet:///modules/ntp/ntp.conf",
# This source file would be located on the puppet master at
# /etc/puppetlabs/puppet/modules/ntp/files/ntp.conf (in Puppet
Enterprise)
# or
# /etc/puppet/modules/ntp/files/ntp.conf (in open source Puppet)
}
Language: Reserved Words and Acceptable
Puppet 3.6 Reference Manual Language: Reserved Words and Acceptable Names 22/325
Language: Reserved Words and Acceptable
Names
Reserved Words
Several words in the Puppet language are reserved. This means they:
Cannot be used as bare word strings you must quote these words if you wish to use them as
strings.
Cannot be used as names for custom functions.
Cannot be used as names for classes.
Cannot be used as names for custom resource types or dened resource types.
The following words are reserved:
and expression operator
case language keyword
class language keyword
default language keyword
define language keyword
else language keyword
elsif language keyword
false boolean value
if language keyword
in expression operator
import language keyword
inherits language keyword
node language keyword
or expression operator
true boolean value
undef special value
unless language keyword
Additionally, you cannot use the name of any existing resource type or function as the name of a
function, and you cannot use the name of any existing resource type as the name of a dened type.
Note: As of Puppet 3, reserved words MAY be used as names for attributes in custom
resource types. This is a change from the behavior of 2.7 and earlier.
Puppet 3.6 Reference Manual Language: Reserved Words and Acceptable Names 23/325
Reserved Class Names
The following are built-in namespaces used by Puppet and so must not be used as class names:
main Puppet automatically creates a main class, which contains any resources not contained
by any other class.
settings The automatically created settings namespace contains variables with the settings
available to the compiler (that is, the puppet masters settings).
Reserved Variable Names
The following variable names are reserved, and you must not assign values to them:
$string If a variable with this name is present, all templates and inline templates in the
current scope will return the value of $string instead of whatever they were meant to return.
This is a bug rather than a deliberate design, and can be tracked at issue #14093.
Every variable name consisting only of numbers, starting with $0 These regex capture
variables are automatically set by regular expressions used in conditional statements, and their
values do not persist outside their associated code block or selector value. Puppets behavior
when these variables are directly assigned a value is undened.
Puppets built-in variables and facts are reserved at top scope, but can be safely re-used at node
or local scope.
If enabled, the $trusted and $facts variables are reserved for facts and cannot be reassigned at
local scopes.
Acceptable Characters in Names
Puppet limits the characters you can use when naming language constructs.
Variables
Variable names begin with a $ (dollar sign) and can include:
Uppercase and lowercase letters
Numbers
Underscores
There is no additional restriction on the rst non-$ character of a variable name. Variable names
are case-sensitive. Note that some variable names are reserved.
Note: In some cases, names containing unsupported characters will still work. These cases
should be considered bugs, and may cease to work at any time. Removal of these bug cases
will not be limited to major releases.
Puppet 3.6 Reference Manual Language: Reserved Words and Acceptable Names 24/325
Variable names should match the following regular expression:
\A\$[a-zA-Z0-9_]+\Z
Variable names can be fully qualiedto refer to variables from foreign scopes. Qualied variable
names look like $class::name::variable_name. They begin with $, the name of the class that
contains the variable, and the :: (double colon) namespace separator, and end with the variables
local name.
Qualied variable names should match the following regular expression:
\A\$([a-z][a-z0-9_]*)?(::[a-z][a-z0-9_]*)*::[a-zA-Z0-9_]+\Z
Classes and Types
The names of classes, dened types, and custom types can consist of one or more namespace
segments. Each namespace segment must begin with a lowercase letter and can include:
Lowercase letters
Numbers
Underscores
Namespace segments should match the following regular expression:
\A[a-z][a-z0-9_]*\Z
The one exception is the top namespace, whose name is the empty string.
Multiple namespace segments can be joined together in a class or type name with the :: (double
colon) namespace separator.
Class names with multiple namespaces should match the following regular expression:
\A([a-z][a-z0-9_]*)?(::[a-z][a-z0-9_]*)*\Z
Note that some class names are reserved, and reserved words cannot be used as class or type
names.
Modules
Module names obey the same rules as individual class/type namespace segments. That is, they
must begin with a lowercase letter and can include:
Lowercase letters
Puppet 3.6 Reference Manual Language: Reserved Words and Acceptable Names 25/325
Numbers
Underscores
Module names should match the following regular expression:
\A[a-z][a-z0-9_]*\Z
Note that reserved words and reserved class names cannot be used as module names.
Parameters
Class and dened type parameters begin with a $ (dollar sign), and their rst non-$ character must
be a lowercase letter. They can include:
Lowercase letters
Numbers
Underscores
Parameter names should match the following regular expression:
\A\$[a-z][a-z0-9_]*\Z
Tags
Tags must begin with a lowercase letter, number, or underscore, and can include:
Lowercase letters
Numbers
Underscores
Colons
Periods
Hyphens
Tag names should match the following regular expression:
\A[a-z0-9_][a-z0-9_:\.\-]*\Z
Resources
Resource titles may contain any characters whatsoever. They are case-sensitive.
Resource names (or namevars) may be limited by the underlying system being managed. (E.g., most
systems have limits on the characters allowed in the name of a user account.) The user is generally
responsible for knowing the name limits on the platforms they manage.
Puppet 3.6 Reference Manual Language: Reserved Words and Acceptable Names 26/325
Nodes
The set of characters allowed in node names is undenedin this version of Puppet. For best future
compatibility, you should limit node names to letters, numbers, periods, underscores, and dashes.
(That is, node names should match /\A[a-z0-9._-]+\Z/.)
Environments
Environment names may contain only numbers and lowercase letters. That is, they must match the
following regular expression:
\A[a-z0-9]+\Z
Language: Resources
Resources are the fundamental unit for modeling system congurations. Each resource describes
some aspect of a system, like a service that must be running or a package that must be installed.
The block of Puppet code that describes a resource is called a resource declaration.
Declaring a resource instructs Puppet to include it in the catalog and manage its state on the target
system. Resource declarations inside a class denitionor dened typeare only added to the catalog
once the class or an instance of the dened type is declared. Virtual resources are only added to the
catalog once they are realized.
Syntax
# A resource declaration:
file { '/etc/passwd':
ensure => file,
owner => 'root',
group => 'root',
mode => '0600',
}
Every resource has a type, a title, and a set of attributes:
type {'title':
attribute => value,
}
See the Type Reference for complete information about Puppets built-in resource types.
Puppet 3.6 Reference Manual Language: Resources 27/325
The general form of a resource declaration is:
The resource type, in lower-case
An opening curly brace
The title, which is a string
A colon
Optionally, any number of attribute and value pairs, each of which consists of:
An attribute name, which is a bare word
A => (arrow, fat comma, or hash rocket)
A value, which can be any data type, depending on what the attribute requires
A trailing comma (note that the comma is optional after the nal attribute/value pair)
Optionally, a semicolon, followed by another title, colon, and attribute block
A closing curly brace
Note that, in the Puppet language, whitespace is fungible.
Type
The type identies what kind of resource it is. Puppet has a large number of built-in resource types,
including les on disk, cron jobs, user accounts, services, and software packages. See here for a list
of built-in resource types.
Puppet can be extended with additional resource types, written in Ruby or in the Puppet language.
Title
The title is an identifying string. It only has to identify the resource to Puppets compiler; it does not
need to bear any relationship to the actual target system.
Titles must be unique per resource type. You may have a package and a service both titled ntp,
but you may only have one service titled ntp. Duplicate titles will cause a compilation failure.
Attributes
Attributes describe the desired state of the resource; each attribute handles some aspect of the
resource.
Each resource type has its own set of available attributes; see the type reference for a complete list.
Most types have a handful of crucial attributes and a larger number of optional ones. Many
attributes have a default value that will be used if a value isnt specied.
Every attribute you declare must have a value; the data type of the value depends on what the
attribute accepts. Most attributes that can take multiple values accept them as an array.
PARAMETERS
Puppet 3.6 Reference Manual Language: Resources 28/325
When discussing resources and types, parameter is a synonym for attribute. Parameter is usually
used when discussing a type, and attribute is usually used when discussing an individual
resource.
Behavior
A resource declaration adds a resource to the catalog, and tells Puppet to manage that resources
state. When Puppet applies the compiled catalog, it will:
Read the actual state of the resource on the target system
Compare the actual state to the desired state
If necessary, change the system to enforce the desired state
Uniqueness
Puppet does not allow you to declare the same resource twice. This is to prevent multiple
conicting values from being declared for the same attribute.
Puppet uses the title and name/namevar to identify duplicate resources if either of these is
duplicated within a given resource type, the compilation will fail.
If multiple classes require the same resource, you can use a class or a virtual resource to add it to
the catalog in multiple places without duplicating it.
Events
If Puppet makes any changes to a resource, it will log those changes as events. These events will
appear in puppet agents log and in the run report, which is sent to the puppet master and
forwarded to any number of report processors.
Parse-Order Independence
Resources are not applied to the target system in the order they are written in the manifests
Puppet will apply the resources in whatever way is most ecient. If a resource must be applied
before or after some other resource, you must explicitly say so. See Relationships for more
information.
Scope Independence
Resources are not subject to scope a resource in any scope may be referenced from any other
scope, and local scopes do not introduce local namespaces for resource titles.
Containment
Resources may be contained by classes and dened types. See Containment for more details.
Special Attributes
Name/Namevar
Puppet 3.6 Reference Manual Language: Resources 29/325
Name/Namevar
Most types have an attribute which identies a resource on the target system. This is referred to as
the namevar, and is often simply called name. For example, the name of a service or package is
the name by which the systems service or package tools will recognize it. The path of a le is its
location on disk.
Namevar values must be unique per resource type, with only rare exceptions (such as exec).
Namevars are not to be confused with the title, which identies a resource to Puppet. However, they
often have the same value, since the namevars value will default to the title if it isnt specied.
Thus, the path of the le example above is /etc/passwd, even though it was never specied.
The distinction between title and namevar lets you use a single, consistently-titled resource to
manage something whose name diers by platform. For example, the NTP service is ntpd on Red
Hat-derived systems, but ntp on Debian and Ubuntu; the service resource could simply be titled
ntp, but could have its name set correctly by platform. Other resources could then form
relationships to it without worrying that its title will change.
Ensure
Many types have an ensure attribute. This generally manages the most fundamental aspect of the
resource on the target system does the le exist, is the service running or stopped, is the
package installed or uninstalled, etc.
Allowed values for ensure vary by type. Most types accept present and absent, but there may be
additional variations. Be sure to check the reference for each type you are working with.
Metaparameters
Some attributes in Puppet can be used with every resource type. These are called metaparameters.
They dont map directly to system state; instead, they specify how Puppet should act toward the
resource.
The most commonly used metaparameters are for specifying order relationships between
resources.
You can see the full list of all metaparameters in the Metaparameter Reference.
Condensed Forms
There are two ways to compress multiple resource declarations. You can also use resource defaults
to reduce duplicate typing.
Array of Titles
If you specify an array of strings as the title of a resource declaration, Puppet will treat it as multiple
resource declarations with an identical block of attributes.
Puppet 3.6 Reference Manual Language: Resources 30/325
file { ['/etc',
'/etc/rc.d',
'/etc/rc.d/init.d',
'/etc/rc.d/rc0.d',
'/etc/rc.d/rc1.d',
'/etc/rc.d/rc2.d',
'/etc/rc.d/rc3.d',
'/etc/rc.d/rc4.d',
'/etc/rc.d/rc5.d',
'/etc/rc.d/rc6.d']:
ensure => directory,
owner => 'root',
group => 'root',
mode => 0755,
}
This example is the same as declaring each directory as a separate resource with the same attribute
block. You can also store an array in a variable and specify the variable as a resource title:
$rcdirectories = ['/etc',
'/etc/rc.d',
'/etc/rc.d/init.d',
'/etc/rc.d/rc0.d',
'/etc/rc.d/rc1.d',
'/etc/rc.d/rc2.d',
'/etc/rc.d/rc3.d',
'/etc/rc.d/rc4.d',
'/etc/rc.d/rc5.d',
'/etc/rc.d/rc6.d']
file { $rcdirectories:
ensure => directory,
owner => 'root',
group => 'root',
mode => 0755,
}
Note that you cannot specify a separate namevar with an array of titles, since it would then be
duplicated across all of the resources. Thus, each title must be a valid namevar value.
Semicolon After Attribute Block
If you end an attribute block with a semicolon rather than a comma, you may specify another title,
another colon, and another complete attribute block, instead of closing the curly braces. Puppet will
treat this as multiple resources of a single type.
file {
'/etc/rc.d':
ensure => directory,
owner => 'root',
Puppet 3.6 Reference Manual Language: Resources 31/325
group => 'root',
mode => 0755;
'/etc/rc.d/init.d':
ensure => directory,
owner => 'root',
group => 'root',
mode => 0755;
'/etc/rc.d/rc0.d':
ensure => directory,
owner => 'root',
group => 'root',
mode => 0755;
}
Adding or Modifying Attributes
Although you cannot declare the same resource twice, you can add attributes to an already-
declared resource. In certain circumstances, you can also override attributes.
Amending Attributes With a Reference
file {'/etc/passwd':
ensure => file,
}
File['/etc/passwd'] {
owner => 'root',
group => 'root',
mode => 0640,
}
The general form of a reference attribute block is:
A reference to the resource in question (or a multi-resource reference)
An opening curly brace
Any number of attribute => value pairs
A closing curly brace
In normal circumstances, this idiom can only be used to add previously unmanaged attributes to a
resource; it cannot override already-specied attributes. However, within an inherited class, you
can use this idiom to override attributes.
Amending Attributes With a Collector
class base::linux {
file {'/etc/passwd':
ensure => file,
Puppet 3.6 Reference Manual Language: Resources 32/325
}
...
}
include base::linux
File <| tag == 'base::linux' |> {
owner => 'root',
group => 'root',
mode => 0640,
}
The general form of a collector attribute block is:
A resource collector that matches any number of resources
An opening curly brace
Any number of attribute => value (or attribute +> value) pairs
A closing curly brace
Much like in an inherited class, you can use the special +> keyword to append values to attributes
that accept arrays. See appending to attributes for more details.
Language: Relationships and Ordering
The order of resources in a Puppet manifest does not matter. Puppet assumes that most resources
are not related to each other and will manage the resources in whatever order is most ecient.
If a group of resources should be managed in a specic order, you must explicitly declare the
relationships.
Syntax
Note that this idiom must be used carefully, if at all:
It can always override already-specied attributes, regardless of class inheritance.
It can aect large numbers of resources at once.
It will implicitly realize any virtual resources that the collector matches. If you are using
virtual resources at all, you must use extreme care when constructing collectors that are
not intended to realize resources, and would be better o avoiding non-realizing
collectors entirely.
Since it ignores class inheritance, you can override the same attribute twice, which results
in a parse-order dependent race where the nal override wins.
Puppet 3.6 Reference Manual Language: Relationships and Ordering 33/325
Relationships can be declared with the relationship metaparameters, chaining arrows, and the
require function.
Relationship Metaparameters
package { 'openssh-server':
ensure => present,
before => File['/etc/ssh/sshd_config'],
}
Puppet uses four metaparameters to establish relationships. Each of them can be set as an attribute
in any resource. The value of any relationship metaparameter should be a resource reference (or
array of references) pointing to one or more target resources.
before
Causes a resource to be applied before the target resource.
require
Causes a resource to be applied after the target resource.
notify
Causes a resource to be applied before the target resource. The target resource will refresh if
the notifying resource changes.
subscribe
Causes a resource to be applied after the target resource. The subscribing resource will
refresh if the target resource changes.
If two resources need to happen in order, you can either put a before attribute in the prior one or a
require attribute in the subsequent one; either approach will create the same relationship. The
same is true of notify and subscribe.
The two examples below create the same ordering relationship:
package { 'openssh-server':
ensure => present,
before => File['/etc/ssh/sshd_config'],
}
file { '/etc/ssh/sshd_config':
ensure => file,
mode => 600,
source => 'puppet:///modules/sshd/sshd_config',
require => Package['openssh-server'],
Puppet 3.6 Reference Manual Language: Relationships and Ordering 34/325
}
The two examples below create the same notication relationship:
file { '/etc/ssh/sshd_config':
ensure => file,
mode => 600,
source => 'puppet:///modules/sshd/sshd_config',
notify => Service['sshd'],
}
service { 'sshd':
ensure => running,
enable => true,
subscribe => File['/etc/ssh/sshd_config'],
}
Chaining Arrows
# ntp.conf is applied first, and will notify the ntpd service if it
changes:
File['/etc/ntp.conf'] ~> Service['ntpd']
You can create relationships between two resources or groups of resources using the -> and ~>
operators.
-> (ordering arrow)
Causes the resource on the left to be applied before the resource on the right. Written with a
hyphen and a greater-than sign.
~> (notication arrow)
Causes the resource on the left to be applied rst, and sends a refresh event to the resource
on the right if the left resource changes. Written with a tilde and a greater-than sign.
OPERANDS
The chaining arrows accept the following types of operands on either side of the arrow:
Resource references, including multi-resource references
Resource declarations
Resource collectors
Note: Arrays of references cannot be chained. To chain multiple resources at once, you must
use a multi-resource reference or a collector.
Puppet 3.6 Reference Manual Language: Relationships and Ordering 35/325
An operand can be shared between two chaining statements, which allows you to link them
together into a timeline:
Package['ntp'] -> File['/etc/ntp.conf'] ~> Service['ntpd']
Since resource declarations can be chained, you can use chaining arrows to make Puppet apply a
section of code in the order that it is written:
# first:
package { 'openssh-server':
ensure => present,
} -> # and then:
file { '/etc/ssh/sshd_config':
ensure => file,
mode => 600,
source => 'puppet:///modules/sshd/sshd_config',
} ~> # and then:
service { 'sshd':
ensure => running,
enable => true,
}
And since collectors can be chained, you can create many-to-many relationships:
Yumrepo <| |> -> Package <| |>
This example would apply all yum repository resources before applying any package resources,
which protects any packages that rely on custom repos.
Note: Chained collectors can potentially cause huge dependency cycles and should be used
carefully. They can also be dangerous when used with virtual resources, which are implicitly
realized by collectors.
Note: Although you can usually chain many resources and/or collectors together
( File['one'] -> File['two'] -> File['three']), the chain can be broken if it includes a
collector whose search expression doesnt match any resources. This is Puppet bug #18399.
Note: Collectors can only search on attributes which are present in the manifests and cannot
see properties that must be read from the target system. For example, if the example above
had been written as Yumrepo <| |> -> Package <| provider == yum |>, it would only
create relationships with packages whose provider attribute had been explicitly set to yum
in the manifests. It would not aect any packages that didnt specify a provider but would
Puppet 3.6 Reference Manual Language: Relationships and Ordering 36/325
REVERSED FORMS
Both chaining arrows have a reversed form ( <- and <~). As implied by their shape, these forms
operate in reverse, causing the resource on their right to be applied before the resource on their
left.
The require Function
The require function declares a class and causes it to become a dependency of the surrounding
container:
class wordpress {
require apache
require mysql
...
}
The above example would cause every resource in the apache and mysql classes to be applied
before any of the resources in the wordpress class.
Unlike the relationship metaparameters and chaining arrows, the require function does not have a
reciprocal form or a notifying form. However, more complex behavior can be obtained by
combining include and chaining arrows inside a class denition:
class apache::ssl {
include site::certificates
# Restart every service in this class if any of our SSL certificates
change on disk:
Class['site::certificates'] ~> Class['apache::ssl']
}
Behavior
Ordering and Notication
Puppet has two types of resource relationships:
Ordering
Ordering with notication
end up using Yum.
Note: As the majority of Puppets syntax is written left-to-right, these reversed forms can be
confusing and are not recommended.
Puppet 3.6 Reference Manual Language: Relationships and Ordering 37/325
An ordering relationship ensures that one resource will be managed before another.
A notication relationship does the same, but also sends the latter resource a refresh event if
Puppet changes the rst resources state. A refresh event causes the recipient to refresh itself.
If a resource receives multiple refresh events, they will be combined and the resource will only
refresh once.
Refreshing
Only certain resource types can refresh themselves. Of the built-in types, these are service, mount,
and exec.
Service resources refresh by restarting their service. Mount resources refresh by unmounting and
then mounting their volume. Exec resources usually do not refresh, but can be made to: setting
refreshonly => true causes the exec to never re unless it receives a refresh event. You can also
set an additional refresh command, which causes the exec to run both commands when it receives
a refresh event.
Autorequire
Certain resource types can autorequire other resources. This creates an ordering relationship
without the user explicitly stating one. Autorequiring is done when applying a catalog. (That is, the
autorequire relationship is not already present in the catalog.)
When Puppet is preparing to sync a resource whose type supports autorequire, it will search the
catalog for any resources that match certain rules. If it nds any, it will process them before that
resource. If Puppet doesnt nd any resources that could be autorequired, thats ne; they wont be
considered a failed dependency.
The type reference contains information on which types can autorequire other resources. Each
types description should state its autorequire behavior, if any. For an example, see the
Autorequires section near the end of the exec types description.
Parse-Order Independence
Relationships are not limited by parse-order. You can declare a relationship with a resource before
that resource has been declared.
Missing Dependencies
If one of the resources in a relationship is never declared, compilation will fail with one of the
following errors:
Could not find dependency <OTHER RESOURCE> for <RESOURCE>
Could not find resource '<OTHER RESOURCE>' for relationship on '<RESOURCE>'.
Failed Dependencies
Puppet 3.6 Reference Manual Language: Relationships and Ordering 38/325
If Puppet fails to apply the prior resource in a relationship, it will skip the subsequent resource and
log the following messages:
notice: <RESOURCE>: Dependency <OTHER RESOURCE> has failures: true
warning: <RESOURCE>: Skipping because of failed dependencies
It will then continue to apply any unrelated resources. Any resources that depend on the skipped
resource will also be skipped.
This helps prevent inconsistent system state by causing a clean failure instead of attempting to
apply a resource whose prerequisites may be broken.
Dependency Cycles
If two or more resources require each other in a loop, Puppet will compile the catalog but will be
unable to apply it. Puppet will log an error like the following, and will attempt to help you identify
the cycle:
err: Could not apply complete catalog: Found 1 dependency cycle:
(<RESOURCE> => <OTHER RESOURCE> => <RESOURCE>)
Try the '--graph' option and opening the resulting '.dot' file in OmniGraffle
or GraphViz
To locate the directory containing the graph les, run puppet agent --configprint graphdir.
Language: Resource Defaults
Resource defaults let you set default attribute values for a given resource type. Any resource
declaration within the area of eect that omits those attributes will inherit the default values.
Syntax
Exec {
path => '/usr/bin:/bin:/usr/sbin:/sbin',
environment => 'RUBYLIB=/opt/puppet/lib/ruby/site_ruby/1.8/',
logoutput => true,
timeout => 180,
}
Note: Although a resource wont be applied if a dependency fails, it can still receive and
respond to refresh events from other, successful, dependencies. This is because refreshes
are handled semi-independently of the normal resource sync process. It is an outstanding
design issue, and may be tracked at issue #7486.
Puppet 3.6 Reference Manual Language: Resource Defaults 39/325
The general form of resource defaults is:
The resource type, capitalized. (If the type has a namespace separator ( ::) in its name, every
segment must be capitalized. E.g., Concat::Fragment.)
An opening curly brace.
Any number of attribute and value pairs.
A closing curly brace.
You can specify defaults for any resource type in Puppet, including dened types.
Behavior
Within the area of eect, every resource of the specied type that omits a given attribute will inherit
that attributes default value.
Attributes that are set explicitly in a resource declaration will always override any default value.
Resource defaults are parse-order independent. A default will aect resource declarations written
both above and below it.
Overriding Defaults From Parent Scopes
Resource defaults declared in the local scope will override any defaults received from parent
scopes.
Overriding of resource defaults is per attribute, not per block of attributes. Thus, local and
inherited resource defaults that dont conict with each other will be merged together.
Area of Eect
Although Puppet 3.x no longer does dynamic variable lookup, it still uses dynamic scope for
resource defaults. See here for a full description of scope rules.
You can declare global resource defaults in the site manifest outside any node denition.
Language: Variables
Facts and Built-In Variables
Puppet has many built-in variables that you can use in your manifests. For a list of these, see
the page on facts and built-in variables.
Puppet 3.6 Reference Manual Language: Variables 40/325
Syntax
Assignment
$content = "some content\n"
Variable names are prexed with a $ (dollar sign). Values are assigned to them with the = (equal
sign) assignment operator.
Any value of any of the normal (i.e. non-regex) data types can be assigned to a variable. Any
statement that resolves to a normal value (including expressions, functions, and other variables)
can be used in place of a literal value. The variable will contain the value that the statement resolves
to, rather than a reference to the statement.
Variables can only be assigned using their short name. That is, a given scope cannot assign values
to variables in a foreign scope.
Resolution
file {'/tmp/testing':
ensure => file,
content => $content,
}
$address_array = [$address1, $address2, $address3]
The name of a variable can be used in any place where a value of its data type would be accepted,
including expressions, functions, and resource attributes. Puppet will replace the name of the
variable with its value.
Interpolation
$rule = "Allow * from $ipaddress"
file { "${homedir}/.vim":
ensure => directory,
...
}
Puppet can resolve variables in double-quoted strings; this is called interpolation.
Inside a double-quoted string, you can optionally surround the name of the variable (the portion
after the $) with curly braces ( ${var_name}). This syntax helps to avoid ambiguity and allows
variables to be placed directly next to non-whitespace characters. These optional curly braces are
only allowed inside strings.
Appending Assignment
Puppet 3.6 Reference Manual Language: Variables 41/325
When creating a local variable with the same name as a variable in top scope, node scope, or a
parent scope, you can optionally append to the received value with the += (plus-equals) appending
assignment operator.
$ssh_users = ['myself', 'someone']
class test {
$ssh_users += ['someone_else']
}
In the example above, the value of $ssh_users inside class test would be ['myself', 'someone',
'someone_else'].
The value appended with the += operator must be the same data type as the received value. This
operator can only be used with strings, arrays, and hashes:
Strings: Will concatenate the two strings.
Arrays: Will add the elements of the appended array to the end of the received array.
Hashes: Will merge the two hashes.
Behavior
Scope
The area of code where a given variable is visible is dictated by its scope. Variables in a given scope
are only available within that scope and its child scopes, and any local scope can locally override the
variables it receives from its parents.
See the section on scope for complete details.
Accessing Out-of-Scope Variables
You can access out-of-scope variables from named scopes by using their qualied names:
$vhostdir = $apache::params::vhostdir
Note that the top scopes name is the empty string thus, the qualied name of a top scope
variable would be, e.g., $::osfamily. See scope for details.
No Reassignment
Unlike most other languages, Puppet only allows a given variable to be assigned once within a
given scope. You may not change the value of a variable, although you may assign a dierent value
to the same variable name in a new scope:
Puppet 3.6 Reference Manual Language: Variables 42/325
# scope-example.pp
# Run with puppet apply --certname www1.example.com scope-example.pp
$myvar = "Top scope value"
node 'www1.example.com' {
$myvar = "Node scope value"
notice( "from www1: $myvar" )
include myclass
}
node 'db1.example.com' {
notice( "from db1: $myvar" )
include myclass
}
class myclass {
$myvar = "Local scope value"
notice( "from myclass: $myvar" )
}
In the example above, $myvar has several dierent values, but only one value will apply to any
given scope.
Parse-Order Dependence
Unlike resource declarations, variable assignments are parse-order dependent. This means you
cannot resolve a variable before it has been assigned.
This is the main way in which the Puppet language fails to be fully declarative.
Naming
Variable names are case-sensitive and can include alphanumeric characters and underscores.
Qualied variable names are prexed with the name of their scope and the :: (double colon)
namespace separator. (For example, the $vhostdir variable from the apache::params class would
be $apache::params::vhostdir.)
See the section on acceptable characters in variable names for more details. Additionally, several
variable names are reserved.
Language: Facts and Built-in Variables
Note: Due to insucient protection of the scope object that gets passed into templates, it is
possible to reassign a variable inside a template and have the new value persist in the Puppet
scope after the template is evaluated. Do not do this. This behavior is considered a bug
rather than designed behavior and may be removed at any point without a deprecation
period.
Puppet 3.6 Reference Manual Language: Facts and Built-in Variables 43/325
Puppet provides many built-in variables that you can use in your manifests. This page covers where
they come from and how to use them.
Facts
Before requesting a catalog from a puppet master (or compiling one locally with puppet apply), a
puppet node will run Facter to collect information about the system.
Puppet receives this information as facts, which are pre-set variables you can use anywhere in your
manifests. Puppet can use both the built-in core facts and any custom facts present in your
modules.
By default, all facts are strings. If you use Facter 2.0 and enable structured facts in Puppet, facts can
contain any data type, including arrays and hashes. At this time, structured facts dont work with
extensions like PuppetDB.
See here for a complete list of built-in facts. Note that the list depends on the version of Facter
you are using.
See here for a guide to writing custom facts. Theyre useful and easy, and most Puppet users
should learn how to make them.
In Puppet Enterprise, any node detail page in the PE console will contain a list of that nodes
facts.
You can run facter -p on one of your nodes to get a complete report of the facts that node will
report to the master.
You can use PuppetDBs APIs to search and report on your entire deployments facts. (PE users
already have PuppetDB installed.)
Classic Facts
All facts appear in Puppet as top-scope variables. They can be accessed in manifests as
$fact_name.
Example, with the osfamily fact:
if $osfamily == 'redhat' {
# ...
}
Benets:Works in all versions of Puppet.
Drawbacks: Facts use the same namespace as normal user-set variables, so the value of a fact
variable can be overridden in a local scope. People usually dont do this with the core facts, but if
you are publishing code that relies on a custom fact, you might need to take into account the way
that code will be invoked in others environments, since they might be using your variable name for
something else. Some people use the $::fact_name idiom to make sure theyre always reading the
top-scope value of that variable; this is messy, but it works reliably.
Puppet 3.6 Reference Manual Language: Facts and Built-in Variables 44/325
The $facts Hash
If you set trusted_node_data = true in puppet.conf on the puppet master,* facts also appear in a
$facts hash. They can be accessed in manifests as $facts[fact_name]. The variable name $facts
will be reserved, so local scopes cannot re-use it.
Example, with the osfamily fact:
if $facts[osfamily] == 'redhat' {
# ...
}
Benets:More readable and maintainable code, by making facts visibly distinct from other variables.
Also, you dont have to use the $::fact_name idiom mentioned above to protect yourself from local
scopes, since the $facts variable can never be overridden or modied.
Drawbacks: Only works with Puppet 3.5 or later, so its currently a bad choice for reusable code.
* Note: The $facts hash is enabled by default when setting trusted_node_data, but it can be
disabled with the immutable_node_data setting.
Trusted Facts
If you set trusted_node_data = true in puppet.conf on the puppet master, a few special trusted
facts will appear in a $trusted hash. They can be accessed in manifests as $trusted[fact_name].
The variable name $trusted will be reserved, so local scopes cannot re-use it.
Normal facts are self-reported by the node, and nothing guarantees their accuracy. Trusted facts
are extracted from the nodes certicate, which can prove that the CA checked and approved them.
This makes them useful for deciding whether a given node should receive sensitive data in its
catalog.
Example, using a certicate extension:
if $trusted[extensions][pp_image_name] == 'storefront_production' {
include private::storefront::private_keys
}
LIST OF TRUSTED FACTS
The $trusted hash looks something like this:
{
authenticated => 'remote',
certname => 'web01.example.com',
Puppet 3.6 Reference Manual Language: Facts and Built-in Variables 45/325
extensions => {
pp_uuid => 'ED803750-E3C7-44F5-
BB08-41A04433FE2E',
pp_image_name => 'storefront_production'
'1.3.6.1.4.1.34380.1.2.1' => 'ssl-termination'
}
}
The available keys are:
authenticated an indication of whether the catalog request was authenticated, as well as
how it was authenticated. The value will be one of:
remote for authenticated remote requests (as with agent/master Puppet congurations)
local for all local requests (as with standalone puppet apply nodes)
false for unauthenticated remote requests (generally only possible if youve congured
auth.conf to allow unauthenticated catalog requests)
certname the nodes subject CN, as listed in its certicate. (When rst requesting its certicate,
the node requests a subject CN matching the value of its certname setting.)
If authenticated is remote, this is the subject CN extracted from the nodes certicate.
If authenticated is local, this is read directly from the certname setting.
If authenticated is false, the value of this key will be an empty string.
extensions a hash containing any custom extensions present in the nodes certicate.
The keys of the hash will be the extension OIDs any OIDs in the ppRegCertExt range will
appear using their short names, and other OIDs will appear as plain dotted numbers.
If no extensions are present or authenticated is local or false, this will be an empty hash.
Puppet Agent Facts
Puppet agent and puppet apply both add several extra pieces of info to their facts before
requesting or compiling a catalog. Like other facts, these are available as either top-scope variables
or elements in the $facts hash.
$clientcert the value of the nodes certname setting. (This is self-reported; for the veried
certicate name, use $trusted['certname'].)
$clientversion the current version of puppet agent.
$clientnoop the value of the nodes noop setting (true or false) at the time of the run.
Variables Set by the Puppet Master
Several variables are set by the puppet master. These are most useful when managing Puppet with
Puppet. (For example, managing puppet.conf with a template.)
Puppet 3.6 Reference Manual Language: Facts and Built-in Variables 46/325
$environment the agent nodes environment.
$servername the puppet masters fully-qualied domain name. (Note that this information is
gathered from the puppet master by Facter, rather than read from the cong les; even if the
masters certname is set to something other than its fully-qualied domain name, this variable
will still contain the servers fqdn.)
$serverip the puppet masters IP address.
$serverversion the current version of puppet on the puppet master.
$settings::<name of setting> the value of any of the masters settings. This is
implemented as a special namespace and these variables must be referred to by their qualied
names. Note that, other than $environment and $clientnoop, the agent nodes settings are not
available in manifests. If you wish to expose them to the master in this version of Puppet, you will
have to create a custom fact.
Variables Set by the Parser
These variables are set in every local scope by the parser during compilation. These are mostly
useful when implementing complex dened types.
$module_name the name of the module that contains the current class or dened type.
$caller_module_name the name of the module in which the specic instanceof the
surrounding dened type was declared. This is only useful when creating versatile dened types
which will be re-used by several modules.
Language: Scope
Scope Basics
A scope is a specic area of code, which is partially isolated from other areas of code. Scopes limit
the reach of:
Variables
Resource defaults
Scopes do not limit the reach of:
Resource titles, which are all global
Resource references, which can refer to a resource declared in any scope
Summary Diagram
Puppet 3.6 Reference Manual Language: Scope 47/325
Any given scope has access to its own contents, and also receives additional contents from its
parent scope, from node scope, and from top scope.
In the diagram above:
Top scope can only access variables and defaults from its own scope.
Node scope can access variables and defaults from its own scope and top scope.
Each of the example::parent, example::other, and example::four classes can access
variables and defaults from their own scope, node scope, and top scope.
The example::child class can access variables and defaults from its own scope,
example::parents scope, node scope, and top scope.
Top Scope
Code that is outside any class denition, type denition, or node denition exists at top scope.
Variables and defaults declared at top scope are available everywhere.
# site.pp
$variable = "Hi!"
class example {
notify {"Message from elsewhere: $variable":}
}
include example
$ puppet apply site.pp
notice: Message from elsewhere: Hi!
Puppet 3.6 Reference Manual Language: Scope 48/325
Node Scope
Code inside a node denitionexists at node scope. Note that since only one node denition can
match a given node, only one node scope can exist at a time.
Variables and defaults declared at node scope are available everywhere except top scope.
# site.pp
$top_variable = "Available!"
node 'puppet.example.com' {
$variable = "Hi!"
notify {"Message from here: $variable":}
notify {"Top scope: $top_variable":}
}
notify {"Message from top scope: $variable":}
$ puppet apply site.pp
notice: Message from here: Hi!
notice: Top scope: Available!
notice: Message from top scope:
In this example, node scope can access top scope variables, but not vice-versa.
Local Scopes
Code inside a class denitionor dened typeexists in a local scope.
Variables and defaults declared in a local scope are only available in that scope and its children.
There are two dierent sets of rules for when scopes are considered related; see scope lookup
rules below.
# /etc/puppet/modules/scope_example/manifests/init.pp
class scope_example {
$variable = "Hi!"
notify {"Message from here: $variable":}
notify {"Node scope: $node_variable Top scope: $top_variable":}
}
# /etc/puppet/manifests/site.pp
$top_variable = "Available!"
node 'puppet.example.com' {
$node_variable = "Available!"
include scope_example
notify {"Message from node scope: $variable":}
}
notify {"Message from top scope: $variable":}
Note: Classes and resources declared at top scope bypass node scope entirely, and so cannot
access variables or defaults from node scope.
Puppet 3.6 Reference Manual Language: Scope 49/325
$ puppet apply site.pp
notice: Message from here: Hi!
notice: Node scope: Available! Top scope: Available!
notice: Message from node scope:
notice: Message from top scope:
In this example, a local scope can see out into node and top scope, but outer scopes cannot see
in.
Overriding Received Values
Variables and defaults declared at node scope can override those received from top scope. Those
declared at local scope can override those received from node and top scope, as well as any parent
scopes. That is: if multiple variables with the same name are available, Puppet will use the most
local one.
# /etc/puppet/modules/scope_example/manifests/init.pp
class scope_example {
$variable = "Hi, I'm local!"
notify {"Message from here: $variable":}
}
# /etc/puppet/manifests/site.pp
$variable = "Hi, I'm top!"
node 'puppet.example.com' {
$variable = "Hi, I'm node!"
include scope_example
}
$ puppet apply site.pp
notice: Message from here: Hi, I'm local!
Resource defaults are processed by attribute rather than as a block. Thus, defaults that declare
dierent attributes will be merged, and only the attributes that conict will be overridden.
# /etc/puppet/modules/scope_example/manifests/init.pp
class scope_example {
File { ensure => directory, }
file {'/tmp/example':}
}
# /etc/puppet/manifests/site.pp
File {
ensure => file,
owner => 'puppet',
Puppet 3.6 Reference Manual Language: Scope 50/325
owner => 'puppet',
}
include scope_example
In this example, /tmp/example would be a directory owned by the puppet user, and would combine
the defaults from top and local scope.
More Details
Scope of External Node Classier Data
Variables provided by an ENC are set at top scope.
However, all of the classes assigned by an ENC are declared at node scope.
This gives approximately the best and most-expected behavior variables from an ENC are
available everywhere, and classes may use node-specic variables.
Named Scopes and Anonymous Scopes
A class denition creates a named scope, whose name is the same as the classs name. Top scope is
also a named scope; its name is the empty string (aka, the null string).
Node scope and the local scopes created by dened resources are anonymous and cannot be
directly referenced.
Accessing Out-of-Scope Variables
Variables declared in named scopes can be referenced directly from anywhere (including scopes
that otherwise would not have access to them) by using their global qualied name.
Qualied variable names are formatted as follows, using the double-colon namespace separator
between segments:
$<NAME OF SCOPE>::<NAME OF VARIABLE>
include apache::params
$local_copy = $apache::params::confdir
This example would set the variable $local_copy to the value of the $confdir variable from the
apache::params class.
Note: this means compilation will fail if the site manifest tries to set a variable that was
already set at top scope by an ENC.
Notes:
Puppet 3.6 Reference Manual Language: Scope 51/325
Variables declared in anonymous scopes can only be accessed normally and do not have global
qualied names.
Scope Lookup Rules
The scope lookup rules determine when a local scope becomes the parent of another local scope.
There are two dierent sets of scope lookup rules: static scope and dynamic scope. This version of
Puppet uses static scope for variables and dynamic scope for resource defaults.
Static Scope
In static scope, parent scopes are only assigned by class inheritance (using the inherits keyword).
Any derived class receives the contents of its base class in addition to the contents of node and top
scope.
All other local scopes have no parents they only receive their own contents, and the contents of
node scope (if applicable) and top scope.
Remember that top scopes name is the empty string (a.k.a, the null string). Thus,
$::my_variable would always refer to the top-scope value of $my_variable, even if
$my_variable has a dierent value in local scope.
Note that a class must be declared in order to access its variables; simply having the class
available in your modules is insucient.
This means the availability of out-of-scope variables is parse order dependent. You
should only access out-of-scope variables if the class accessing them can guarantee that
the other class is already declared, usually by explicitly declaring it with include before
trying to read its variables.
Note: To help users prepare, Puppet 2.7 will print warnings to its log le whenever a
variables value would be dierent under static scope in Puppet 3. More details about the
elimination of dynamic scope can be found here.
Static scope has the following characteristics:
Scope contents are predictable and do not depend on parse order.
Scope contents can be determined simply by looking at the relevant class denition(s); the
place where a class or type is declared has no eect. (The only exception is node
denitions if a class is declared outside a node, it does not receive the contents of node
scope.)
Puppet 3.6 Reference Manual Language: Scope 52/325
This version of Puppet uses static scope for looking up variables.
Dynamic Scope
In dynamic scope, parent scopes are assigned by both inheritance and declaration, with preference
being given to inheritance. The full list of rules is:
Each scope has only one parent, but may have an unlimited chain of grandparents, and receives
the merged contents of all of them (with nearer ancestors overriding more distant ones).
The parent of a derived class is its base class.
The parent of any other class or dened resource is the rstscope in which it was declared.
When you declare a derived class whose base class hasnt already been declared, the base class
is immediately declared in the current scope, and its parent assigned accordingly. This eectively
inserts the base class between the derived class and the current scope. (If the base class has
already been declared elsewhere, its existing parent scope is not changed.)
This version of Puppet uses dynamic scope for resource defaults.
Messy Under-the-Hood Details
Node scope only exists if there is at least one node denition in the site manifest (or one has
been imported into it). If no node denitions exist, then ENC classes get declared at top scope.
Although top scope and node scope are described above as being special scopes, they are
actually implemented as part of the chain of parent scopes, with node scope being a child of top
scope and the parent of any classes declared inside the node denition. However, since the move
to static scoping causes them to behave as little islands of dynamic scoping in a statically scoped
world, its simpler to think of them as special cases.
If you ignore best practices and use node inheritance, the rules of parent scope assignment treat
node denitions like classes; that is, the base node becomes the parent scope of the derived
node, and normal dynamic scoping will apply to the classes declared in each of the two
denitions. Note that this will usually yield the opposite result of whatever you are trying to
achieve.
Language: Conditional Statements
Dynamic scope has the following characteristics:
A scopes parent cannot be identied by looking at the denition of a class you must
examine every place where the class or resource may have been declared.
In some cases, you can only determine a scopes contents by executing the code.
Since classes may be declared multiple times with the include function, the contents of a
given scope are parse-order dependent.
Puppet 3.6 Reference Manual Language: Conditional Statements 53/325
Conditional statements let your Puppet code behave dierently in dierent situations. They are
most helpful when combined with facts or with data retrieved from an external source.
Summary
Puppet supports if and unless statements, case statements, and selectors.
An if statement:
if $is_virtual == 'true' {
warning('Tried to include class ntp on virtual machine; this node may be
misclassified.')
}
elsif $operatingsystem == 'Darwin' {
warning('This NTP module does not yet work on our Mac laptops.')
}
else {
include ntp
}
An unless statement:
unless $memorysize > 1024 {
$maxclient = 500
}
A case statement:
case $operatingsystem {
'Solaris': { include role::solaris }
'RedHat', 'CentOS': { include role::redhat }
/^(Debian|Ubuntu)$/:{ include role::debian }
default: { include role::generic }
}
A selector:
$rootgroup = $osfamily ? {
'Solaris' => 'wheel',
/(Darwin|FreeBSD)/ => 'wheel',
default => 'root',
}
file { '/etc/passwd':
ensure => file,
owner => 'root',
group => $rootgroup,
}
Puppet 3.6 Reference Manual Language: Conditional Statements 54/325
If Statements
If statements take a boolean condition and an arbitrary block of Puppet code, and will only
execute the block if the condition is true. They can optionally include elsif and else clauses.
Syntax
if $is_virtual == 'true' {
# Our NTP module is not supported on virtual machines:
warn( 'Tried to include class ntp on virtual machine; this node may be
misclassified.' )
}
elsif $operatingsystem == 'Darwin' {
warn ( 'This NTP module does not yet work on our Mac laptops.' )
}
else {
# Normal node, include the class.
include ntp
}
The general form of an if statement is:
The if keyword
A condition
A pair of curly braces containing any Puppet code
Optionally: the elsif keyword, another condition, and a pair of curly braces containing Puppet
code
Optionally: the else keyword and a pair of curly braces containing Puppet code
Behavior
Puppets if statements behave much like those in any other language. The if condition is
evaluated rst and, if it is true, only the if code block is executed. If it is false, each elsif
condition (if present) is tested in order, and if all conditions fail, the else code block (if present) is
executed.
If none of the conditions in the statement match and there is no else block, Puppet will do nothing
and move on.
If statements will execute a maximum of one code block.
Conditions
The condition(s) of an if statement may be any fragment of Puppet code that resolves to a
boolean value. This includes:
Variables
Puppet 3.6 Reference Manual Language: Conditional Statements 55/325
Expressions, including arbitrarily nested and and or expressions
Functions that return values
Fragments that resolve to non-boolean values will be automatically converted to booleans as
described here.
Static values may also be conditions, although doing this would be pointless.
REGEX CAPTURE VARIABLES
If you use the regular expression match operator in a condition, any captures from parentheses in
the pattern will be available inside the associated code block as numbered variables ( $1, $2, etc.),
and the entire match will be available as $0:
if $hostname =~ /^www(\d+)\./ {
notice("Welcome to web server number $1")
}
This example would capture any digits from a hostname like www01 and www02 and store them in
the $1 variable.
These are not normal variables, and have some special behaviors:
The values of the numbered variables do not persist outside the code block associated with the
pattern that set them.
In nested conditionals, each conditional has its own set of values for the set of numbered
variables. At the end of an interior statement, the numbered variables are reset to their previous
values for the remainder of the outside statement. (This causes conditional statements to act like
local scopes, but only with regard to the numbered variables.)
Unless Statements
Unless statements work like reversed if statements. They take a boolean condition and an
arbitrary block of Puppet code, and will only execute the block if the condition is false. They cannot
include elsif or else clauses.
Syntax
unless $memorysize > 1024 {
$maxclient = 500
}
The general form of an unless statement is:
The unless keyword
A condition
Puppet 3.6 Reference Manual Language: Conditional Statements 56/325
A pair of curly braces containing any Puppet code
If an else or elsif clause is included in an unless statement, it is a syntax error and will cause
compilation to fail.
Behavior
The condition is evaluated rst and, if it is false, the code block is executed. If the condition is true,
Puppet will do nothing and move on.
Conditions
The condition(s) of an unless statement may be any fragment of Puppet code that resolves to a
boolean value. This includes:
Variables
Expressions, including arbitrarily nested and and or expressions
Functions that return values
Fragments that resolve to non-boolean values will be automatically converted to booleans as
described here.
Static values may also be conditions, although doing this would be pointless.
REGEX CAPTURE VARIABLES
Although unless statements receive regex capture variables like if statements, they generally
cant be used, since the code in the statement will only be executed if the condition didnt match
anything. Compound conditions can cause the capture variables to be set inside the statement, but
this is essentially useless.
Case Statements
Like if statements, case statements choose one of several blocks of arbitrary Puppet code to
execute. They take a control expression and a list of cases and code blocks, and will execute the
rst block whose case value matches the control expression.
Syntax
case $operatingsystem {
'Solaris': { include role::solaris } # apply the solaris class
'RedHat', 'CentOS': { include role::redhat } # apply the redhat class
/^(Debian|Ubuntu)$/:{ include role::debian } # apply the debian class
default: { include role::generic } # apply the generic class
}
The general form of a case statement is:
Puppet 3.6 Reference Manual Language: Conditional Statements 57/325
The case keyword
A control expression (see below)
An opening curly brace
Any number of possible matches, which consist of:
A case (see below) or comma-separated list of cases
A colon
A pair of curly braces containing any arbitrary Puppet code
A closing curly brace
Behavior
Puppet compares the control expression to each of the cases, in the order they are listed. It will
execute the block of code associated with the rstmatching case, and ignore the remainder of the
statement.
Basic cases are compared with the == operator (which is case-insensitive).
Regular expression cases are compared with the =~ operator (which is case-sensitive).
The special default case matches anything.
If none of the cases match, Puppet will do nothing and move on.
Case statements will execute a maximum of one code block.
Control Expressions
The control expression of a case statement may be any fragment of Puppet code that resolves to a
normal value. This includes:
Variables
Expressions
Functions that return values
Cases
Cases may be any of the following:
A literal value (remember to quote strings)
A variable
A function call that returns a value
A regular expression
The special bare word value default
Note that you cannot use arbitrary expressions or selectors as cases.
You may use a comma-separated list of cases to associate more than one case with the same block
Puppet 3.6 Reference Manual Language: Conditional Statements 58/325
You may use a comma-separated list of cases to associate more than one case with the same block
of code.
Normal values are compared to the control expression using the == operator, and regular
expressions are compared with the =~ operator. The special default case matches any control
expression.
Cases are compared in the order that they are written in the manifest if more than one case
might match for a given node, the rst one will win. The one exception is the special default case,
which will only be used as a last resort regardless of its position in the list.
REGEX CAPTURE VARIABLES
If you use regular expression cases, any captures from parentheses in the pattern will be available
inside the associated code block as numbered variables ( $1, $2, etc.), and the entire match will be
available as $0:
if $hostname =~ /^www(\d+)\./ {
notice("Welcome to web server number $1")
}
This example would capture any digits from a hostname like www01 and www02 and store them in
the $1 variable.
These are not normal variables, and have some special behaviors:
The values of the numbered variables do not persist outside the code block associated with the
pattern that set them.
In nested conditionals, each conditional has its own set of values for the set of numbered
variables. At the end of an interior statement, the numbered variables are reset to their previous
values for the remainder of the outside statement. (This causes conditional statements to act like
local scopes, but only with regard to the numbered variables.)
ASIDE: BEST PRACTICES
Case statements should usually have a default case.
If the rest of your cases are meant to be comprehensive, putting a fail('message') call
in the default case makes your code more robust by protecting against mystery failures
due to behavior changes elsewhere in your manifests.
If your cases arent comprehensive and nodes that match none should do nothing, write a
default case with an empty code block ( default: {}). This makes your intention obvious
to the next person who has to maintain your code.
Puppet 3.6 Reference Manual Language: Conditional Statements 59/325
Selectors
Selector statements are similar to case statements, but return a value instead of executing a code
block.
Location
Selectors must be used at places in the code where a plain value is expected. This includes:
Variable assignments
Resource attributes
Function arguments
Resource titles
A value in another selector
Expressions
Selectors are not legal in:
A case in another selector
A case in a case statement
Syntax
Selectors resemble a cross between a case statement and the ternary operator found in other
languages.
$rootgroup = $osfamily ? {
'Solaris' => 'wheel',
/(Darwin|FreeBSD)/ => 'wheel',
default => 'root',
}
file { '/etc/passwd':
ensure => file,
owner => 'root',
group => $rootgroup,
}
In the example above, the value of $rootgroup is determined using the value of $osfamily.
The general form of a selector is:
A control variable
ASIDE: BEST PRACTICES
For readabilitys sake, you should generally only use selectors in variable assignments.
Puppet 3.6 Reference Manual Language: Conditional Statements 60/325
The ? (question mark) keyword
An opening curly brace
Any number of possible matches, each of which consists of:
A case
The => (fat comma) keyword
A value
A trailing comma
A closing curly brace
Behavior
The entire selector statement is treated as a single value.
Puppet compares the control variable to each of the cases, in the order they are listed. When it nds
a matching case, it will treat that value as the value of the statement and ignore the remainder of
the statement.
Basic cases are compared with the == operator (which is case-insensitive).
Regular expression cases are compared with the =~ operator (which is case-sensitive).
The special default case matches anything.
If none of the cases match, Puppet will fail compilation with a parse error. Consequently, a default
case should be considered mandatory.
Control Variables
Control variables in selectors must be variables or functions that return values. You cannot use
expressions as control variables.
Cases
Cases may be any of the following:
A literal value (remember to quote strings)
A variable
A function call that returns a value
A regular expression
The special bare word value default
Note that you cannot use arbitrary expressions or selectors as cases.
Unlike in case statements, you cannot use lists of cases. If you need more than one case associated
with a single value, you must use a regular expression.
Puppet 3.6 Reference Manual Language: Conditional Statements 61/325
Normal values are compared to the control variable using the == operator, and regular expressions
are compared with the =~ operator. The special default case matches any control variable.
Cases are compared in the order that they are written in the manifest; thus, the default case (if
any) must be at the end of the list.
REGEX CAPTURE VARIABLES
If you use regular expression cases, any captures from parentheses in the pattern will be available
inside the associated value as numbered variables ( $1, $2, etc.), and the entire match will be
available as $0:
$system = $operatingsystem ? {
/(RedHat|Debian)/ => "our system is $1",
default => "our system is unknown",
}
These are not normal variables, and have some special behaviors:
The values of the numbered variables do not persist outside the value associated with the
pattern that set them.
In nested conditionals, each conditional has its own set of values for the set of numbered
variables. At the end of an interior statement, the numbered variables are reset to their previous
values for the remainder of the outside statement. (This causes conditional statements to act like
local scopes, but only with regard to the numbered variables.)
Values
Values may be any of the following:
Any literal value, with the exception of hash literals
A variable
A function call that returns a value
Another selector
Note that you cannot use arbitrary expressions as values.
Language: Expressions
Expressions resolve to values and can be used in most of the places where values of the standard
data types are required. Expressions can be compounded with other expressions and the entire
combined expression will resolve to a single value.
Most expressions resolve to boolean values. They are particularly useful as conditions in
conditional statements.
Puppet 3.6 Reference Manual Language: Expressions 62/325
Location
Expressions can be used in the following places:
The operand of another expression
The condition of an if statement
The control expression of a case statement
The assignment of a variable
The value of a resource attribute
The argument(s) of a function call
They cannot be used in selectors or as resource titles.
Syntax
An expression consists of two operands separated by an operator; the only operator that takes one
operand is ! (not).
5 < 9
($operatingsystem != 'Solaris')
$kernel in ['linux', 'solaris']
!str2bool($is_virtual)
In the examples above, the operators are <, !=, in, and !.
Optionally, expressions can be surrounded by parentheses.
Operands
Operands in an expression may be:
Literal values
Variables
Other expressions
Function calls which return values
The data type of each operand is dictated by the operator. See the list of operators below for
details.
When creating compound expressions by using other expressions as operands, you should use
parentheses for clarity:
(90 < 7) and ('Solaris' == 'Solaris') # resolves to false
(90 < 7) or ('solaris' in ['linux', 'solaris']) # resolves to true
Puppet 3.6 Reference Manual Language: Expressions 63/325
Order of Operations
Compound expressions are evaluated in a standard order of operations. However, parentheses will
override the order of operations:
# This example will resolve to 30, rather than 23.
notice( (7+8)*2 )
For the sake of clarity, we recommend using parentheses in all but the simplest compound
expressions.
The precedence of operators, from highest to lowest:
Comparison Operators
Comparison operators have the following traits:
They take operands of several data types
They resolve to boolean values
== (equality)
Resolves to true if the operands are equal. Accepts the following types of operands:
Numbers Tests simple equality.
Strings Case-insensitively tests whether two strings are identical.
Arrays and hashes Tests whether two arrays or hashes are identical.
Booleans Tests whether two booleans are the same value.
!= (non-equality)
Resolves to false if the operands are equal. Behaves similarly to ==.
< (less than)
1. ! (not)
2. in
3. * and / (multiplication and division)
4. - and + (addition and subtraction)
5. << and >> (left shift and right shift)
6. == and != (equal and not equal)
7. >=, <=, >, and < (greater or equal, less or equal, greater than, and less than)
8. and
9. or
Puppet 3.6 Reference Manual Language: Expressions 64/325
Resolves to true if the left operand is smaller than the right operand. Accepts numbers.
The behavior of this operator when used with strings is undened.
> (greater than)
Resolves to true if the left operand is bigger than the right operand. Accepts numbers.
The behavior of this operator when used with strings is undened.
<= (less than or equal to)
Resolves to true if the left operand is smaller than or equal to the right operand. Accepts numbers.
The behavior of this operator when used with strings is undened.
>= (greater than or equal to)
Resolves to true if the left operand is bigger than or equal to the right operand. Accepts numbers.
The behavior of this operator when used with strings is undened.
=~ (regex match)
This operator is non-transitive with regard to data types: it accepts a string as the left operand and
a regular expression as the right operand.
Resolves to true if the left operand matches the regular expression.
!~ (regex non-match)
This operator is non-transitive with regard to data types: it accepts a string as the left operand and
a regular expression as the right operand.
Resolves to false if the left operand matches the regular expression.
in
Resolves to true if the right operand contains the left operand. This operator is case sensitive.
This operator is non-transitive with regard to data types: it accepts a string as the left operand, and
the following types of right operands:
Strings Tests whether the left operand is a substring of the right.
Arrays Tests whether one of the members of the array is identical to the left operand.
Hashes Tests whether the hash has a key named after the left operand.
Examples:
Puppet 3.6 Reference Manual Language: Expressions 65/325
'eat' in 'eaten' # resolves to TRUE
'Eat' in 'eaten' # resolves to FALSE
'eat' in ['eat', 'ate', 'eating'] # resolves to TRUE
'eat' in { 'eat' => 'present tense', 'ate' => 'past tense'} # resolves to
TRUE
'eat' in { 'present' => 'eat', 'past' => 'ate' } # resolves to FALSE
Boolean Operators
Boolean Operators have the following traits:
They take boolean operands; if another data type is given, it will be automatically converted to
boolean
They resolve to boolean values
These expressions are most useful when creating compound expressions.
and
Resolves to true if both operands are true, otherwise resolves to false.
or
Resolves to true if either operand is true.
! (not)
Takes one operand:
$my_value = true
notice ( !$my_value ) # Will resolve to false
Resolves to true if the operand is false, and false if the operand is true.
Arithmetic Operators
Arithmetic Operators have the following traits:
They take two numeric operands
They resolve to numeric values
+ (addition)
Resolves to the sum of the two operands.
- (subtraction)
Resolves to the dierence of the two operands.
Puppet 3.6 Reference Manual Language: Expressions 66/325
/ (division)
Resolves to the quotient of the two operands.
* (multiplication)
Resolves to the product of the two operands.
% (modulo)
Resolves to the remainder of dividing the rst operand by the second operand. (E.g. 5 % 2 would
resolve to 1.)
<< (left shift)
Left bitwise shift: shifts the left operand by the number of places specied by the right operand.
This is equivalent to rounding each operand down to the nearest integer and multiplying the left
operand by 2 to the power of the right operand.
>> (right shift)
Right bitwise shift: shifts the left operand by the number of places specied by the right operand.
This is equivalent to rounding each operand down to the nearest integer and dividing the left
operand by 2 to the power of the right operand.
Backus Naur Form
With the exception of the in operator, the available operators in Backus Naur Form are:
<exp> ::= <exp> <arithop> <exp>
| <exp> <boolop> <exp>
| <exp> <compop> <exp>
| <exp> <matchop> <regex>
| ! <exp>
| - <exp>
| "(" <exp> ")"
| <rightvalue>
<arithop> ::= "+" | "-" | "/" | "*" | "<<" | ">>"
<boolop> ::= "and" | "or"
<compop> ::= "==" | "!=" | ">" | ">=" | "<=" | "<"
<matchop> ::= "=~" | "!~"
<rightvalue> ::= <variable> | <function-call> | <literals>
<literals> ::= <float> | <integer> | <hex-integer> | <octal-integer> | <quoted-
string>
<regex> ::= '/regex/'
Puppet 3.6 Reference Manual Language: Expressions 67/325
Language: Functions
Functions are pre-dened chunks of Ruby code which run during compilation. Most functions
either return values or modify the catalog.
Puppet includes several built-in functions, and more are available in modules on the Puppet Forge,
particularly the puppetlabs-stdlib module. You can also write custom functions and put them in
your own modules.
Syntax
file {'/etc/ntp.conf':
ensure => file,
content => template('ntp/ntp.conf'),
}
include apache2
if str2bool($is_virtual) {
include ntp::disabled
}
else {
include ntp
}
# str2bool is part of the puppetlabs-stdlib module; install it with
# sudo puppet module install puppetlabs-stdlib
In the examples above, template, include, and str2bool are all functions. template and
str2bool return values, and include modies the catalog by causing a class to be applied.
The general form of a function call is:
The name of the function, as a bare word
An opening parenthesis, which is optional for statements but mandatory for rvalues
Any number of arguments, separated with commas; the number and type of arguments are
controlled by the function
A closing parenthesis, if an open parenthesis was used
Behavior
There are two types of Puppet functions:
Rvalues return values and can be used anywhere a normal value is expected. (This includes
resource attributes, variable assignments, conditions, selector values, the arguments of other
See the Function Reference for complete info about Puppets built-in functions.
Puppet 3.6 Reference Manual Language: Functions 68/325
resource attributes, variable assignments, conditions, selector values, the arguments of other
functions, etc.) These values can come from a variety of places; the template function reads and
evaluates a template to return a string, and stdlibs str2bool and num2bool functions convert
values from one data type to another.
Statements should stand alone and do some form of work, which can be anything from logging a
message (like notice), to modifying the catalog in progress (like include), to causing the entire
compilation to fail ( fail). Statements do not return usable values.
All functions run during compilation, which means they can only access the commands and data
available on the puppet master. To perform tasks on, or collect data from, an agent node, you must
use a resource or a custom fact.
Arguments
Each function denes how many arguments it takes and what data types it expects those arguments
to be. These should be documented in the functions :doc string, which can be extracted and
included in the function reference.
Functions may accept any of Puppets standard data types. The values passed to the functions Ruby
code will be converted to Ruby objects as follows:
Puppet type Ruby type
boolean boolean
undef the empty string
string string
resource reference Puppet::Resource
number string
array array
hash hash
Language: Classes
Classes are named blocks of Puppet code, which are stored in modules for later use and are not
applied until they are invoked by name. They can be added to a nodes catalog by either declaring
them in your manifests or by assigning them from an ENC.
Classes generally congure large or medium-sized chunks of functionality, such as all of the
packages, cong les, and services needed to run an application.
Dening Classes
Puppet 3.6 Reference Manual Language: Classes 69/325
Dening a class makes it available for later use. It doesnt yet add any resources to the catalog; to
do that, you must declare it (see below) or assign it from an ENC.
Syntax
# A class with no parameters
class base::linux {
file { '/etc/passwd':
owner => 'root',
group => 'root',
mode => '0644',
}
file { '/etc/shadow':
owner => 'root',
group => 'root',
mode => '0440',
}
}
# A class with parameters
class apache ($version = 'latest') {
package {'httpd':
ensure => $version, # Using the class parameter from above
before => File['/etc/httpd.conf'],
}
file {'/etc/httpd.conf':
ensure => file,
owner => 'httpd',
content => template('apache/httpd.conf.erb'), # Template from a module
}
service {'httpd':
ensure => running,
enable => true,
subscribe => File['/etc/httpd.conf'],
}
}
The general form of a class denition is:
The class keyword
The name of the class
An optional set of parameters, which consists of:
An opening parenthesis
A comma-separated list of parameters, each of which consists of:
A new variable name, including the $ prex
An optional equals (=) sign and default value (any data type)
An optional trailing comma after the last parameter
Puppet 3.6 Reference Manual Language: Classes 70/325
A closing parenthesis
Optionally, the inherits keyword followed by a single class name
An opening curly brace
A block of arbitrary Puppet code, which generally contains at least one resource declaration
A closing curly brace
Class Parameters and Variables
Parameters allow a class to request external data. If a class needs to congure itself with data other
than facts, that data should usually enter the class via a parameter.
Each class parameter can be used as a normal variable inside the class denition. The values of
these variables are not set with normal assignment statements or read from top or node scope;
instead, they are automatically set when the class is declared.
Note that if a class parameter lacks a default value, the user of the module must set a value
themselves (either in their external data or an override). As such, you should supply defaults
wherever possible.
Location
Class denitions should be stored in modules. Puppet is automatically aware of classes in modules
and can autoload them by name.
Classes should be stored in their modules manifests/ directory as one class per le, and each
lename should reect the name of its class; see Module Fundamentals and Namespaces and
Autoloading for more details.
OTHER LOCATIONS
Most users should only load classes from modules. However, you can also put classes in the
following additional locations:
The main manifest. If you do so, they may be placed anywhere in the le and are not
parse-order dependent.
Imported manifests. If you do so, you must import the le containing the class before you
may declare it.
Other class denitions. This puts the interior class under the exterior classs namespace,
causing its real name to be something other than the name with which it was dened. It
does not cause the interior class to be automatically declared along with the exterior
class. Nested classes cannot be autoloaded; in order for the interior class to be visible to
Puppet, the manifest containing it must have been forcibly loaded, either by autoloading
the outermost class, using an import statement, or placing the entire nested structure in
the site manifest. Although nesting classes is not yet formally deprecated, it is very much
not recommended.
Puppet 3.6 Reference Manual Language: Classes 71/325
Containment
A class contains all of its resources. This means any relationships formed with the class as a whole
will be extended to every resource in the class.
Classes can also contain other classes, but you must manually specify that a class should be
contained. For details, see the Containing Classes section of the Containment page.
Auto-Tagging
Every resource in a class gets automatically tagged with the classs name (and each of its
namespace segments).
Inheritance
Classes can be derived from other classes using the inherits keyword. This allows you to make
special-case classes that extend the functionality of a more general base class.
Inheritance causes three things to happen:
When a derived class is declared, its base class is automatically declared rst(if it wasnt already
declared elsewhere).
The base class becomes the parent scope of the derived class, so that the new class receives a
copy of all of the base classs variables and resource defaults.
Code in the derived class is given special permission to override any resource attributes that
were set in the base class.
Note: This version of Puppet does not support using parameterized classes for inheritable
base classes. The base class must have no parameters.
ASIDE: WHEN TO INHERIT
Class inheritance should be used very sparingly, generally only in the following situations:
When you need to override resource attributes in the base class.
To let a params class provide default values for another classs parameters:
class example ($my_param = $example::params::myparam) inherits
example::params { ... }
This pattern works by guaranteeing that the params class is evaluated before Puppet
attempts to evaluate the main classs parameter list. It is especially useful when you want
your default values to change based on system facts and other data, since it lets you
isolate and encapsulate all that conditional logic.
Puppet 3.6 Reference Manual Language: Classes 72/325
OVERRIDING RESOURCE ATTRIBUTES
The attributes of any resource in the base class can be overridden with a reference to the resource
you wish to override, followed by a set of curly braces containing attribute => value pairs:
class base::freebsd inherits base::unix {
File['/etc/passwd'] {
group => 'wheel'
}
File['/etc/shadow'] {
group => 'wheel'
}
}
This is identical to the syntax for adding attributes to an existing resource, but in a derived class, it
gains the ability to rewrite resources instead of just adding to them. Note that you can also use
multi-resource references here.
You can remove an attributes previous value without setting a new one by overriding it with the
special value undef:
class base::freebsd inherits base::unix {
File['/etc/passwd'] {
group => undef,
}
}
This causes the attribute to be unmanaged by Puppet.
APPENDING TO RESOURCE ATTRIBUTES
Some resource attributes (such as the relationship metaparameters) can accept multiple values in
an array. When overriding attributes in a derived class, you can add to the existing values instead of
In nearly all other cases, inheritance is unnecessary complexity. If you need some classs
resources declared before proceeding further, you can include it inside another classs
denition. If you need to read internal data from another class, you should generally use
qualied variable namesinstead of assigning parent scopes. If you need to use an anti-
class pattern (e.g. to disable a service that is normally enabled), you can use a class
parameter to override the standard behavior.
Note also that you can use resource collectors to override resource attributes in unrelated
classes, although this feature should be handled with care.
Note: If a base class declares other classes with the resource-like syntax, a class derived from
it cannot override the class parameters of those inner classes. This is a known bug.
Puppet 3.6 Reference Manual Language: Classes 73/325
replacing them by using the +> (plusignment) keyword instead of the standard => hash rocket:
class apache {
service {'apache':
require => Package['httpd'],
}
}
class apache::ssl inherits apache {
# host certificate is required for SSL to function
Service['apache'] {
require +> [ File['apache.pem'], File['httpd.conf'] ],
# Since `require` will retain its previous values, this is equivalent
to:
# require => [ Package['httpd'], File['apache.pem'], File['httpd.conf']
],
}
}
Declaring Classes
Declaring a class in a Puppet manifest adds all of its resources to the catalog. You can declare
classes in node denitions, at top scope in the site manifest, and in other classes or dened types.
Declaring classes isnt the only way to add them to the catalog; you can also assign classes to nodes
with an ENC.
Classes are singletons although a given class may have very dierent behavior depending on
how its parameters are set, the resources in it will only be evaluated once per compilation.
Include-Like vs. Resource-Like
Puppet has two main ways to declare classes: include-like and resource-like.
INCLUDE-LIKE BEHAVIOR
The include, require, contain, and hiera_include functions let you safely declare a class
multiple times; no matter how many times you declare it, a class will only be added to the catalog
once. This can allow classes or dened types to manage their own dependencies, and lets you
create overlapping role classes where a given node may have more than one role.
Include-like behavior relies on external data and defaults for class parameter values, which allows
the external data source to act like cascading conguration les for all of your classes. When a class
is declared, Puppet will try the following for each of its parameters:
Note: These two behaviors should not be mixed for a given class. Puppets behavior when
declaring or assigning a class with both styles is undened, and will sometimes work and
sometimes cause compilation failures.
Puppet 3.6 Reference Manual Language: Classes 74/325
RESOURCE-LIKE BEHAVIOR
Resource-like class declarations require that you only declare a given class once. They allow you to
override class parameters at compile time, and will fall back to external data for any parameters you
dont override. When a class is declared, Puppet will try the following for each of its parameters:
Using include
The include function is the standard way to declare classes.
1. Request a value from the external data source, using the key <class name>::<parameter name>.
(For example, to get the apache classs version parameter, Puppet would search for
apache::version.)
2. Use the default value.
3. Fail compilation with an error if no value can be found.
Aside: Best Practices
Most users in most situations should use include-like declarations and set parameter values
in their external data. However, compatibility with earlier versions of Puppet may require
compromises. See Aside: Writing for Multiple Puppet Versions below for details.
Version Note: Automatic external parameter lookup was a new feature in Puppet 3. Puppet
2.7 and earlier could only use default values or override values from resource-like
declarations. See below for more details.
1. Use the override value from the declaration, if present.
2. Request a value from the external data source, using the key <class name>::<parameter name>.
(For example, to get the apache classs version parameter, Puppet would search for
apache::version.)
3. Use the default value.
4. Fail compilation with an error if no value can be found.
Aside: Why Do Resource-Like Declarations Have to Be Unique?
This is necessary to avoid paradoxical or conicting parameter values. Since overridden
values from the class declaration always win, are computed at compile-time, and do not have
a built-in hierarchy for resolving conicts, allowing repeated overrides would cause catalog
compilation to be unreliable and parse-order dependent.
This was the original reason for adding external data bindings to include-like declarations:
since external data is set before compile-time and has a xed hierarchy,the compiler can
safely rely on it without risk of conicts.
Puppet 3.6 Reference Manual Language: Classes 75/325
include base::linux
include base::linux # no additional effect; the class is only declared once
include base::linux, apache # including a list
$my_classes = ['base::linux', 'apache']
include $my_classes # including an array
The include function uses include-like behavior. (Multiple declarations OK; relies on external data
for parameters.) It can accept:
A single class
A comma-separated list of classes
An array of classes
Using require
The require function (not to be confused with the require metaparameter) declares one or more
classes, then causes them to become a dependency of the surrounding container.
define apache::vhost ($port, $docroot, $servername, $vhost_name) {
require apache
...
}
In the above example, Puppet will ensure that every resource in the apache class gets applied
before every resource in any apache::vhost instance.
The require function uses include-like behavior. (Multiple declarations OK; relies on external data
for parameters.) It can accept:
A single class
A comma-separated list of classes
An array of classes
Using contain
The contain function is meant to be used inside another class denition.It declares one or more
classes, then causes them to become contained by the surrounding class. For details, see the
Containing Classes section of the Containment page.
class ntp {
file { '/etc/ntp.conf':
...
require => Package['ntp'],
notify => Class['ntp::service'],
Puppet 3.6 Reference Manual Language: Classes 76/325
}
contain ntp::service
package { 'ntp':
...
}
}
In the above example, any resource that forms a before or require relationship with class ntp will
also be applied before or after class ntp::service, respectively.
The contain function uses include-like behavior. (Multiple declarations OK; relies on external data
for parameters.) It can accept:
A single class
A comma-separated list of classes
An array of classes
Using hiera_include
The hiera_include function requests a list of class names from Hiera, then declares all of them.
Since it uses the array resolution type, it will get a combined list that includes classes from every
level of the hierarchy. This allows you to abandon node denitionsand use Hiera like a lightweight
ENC.
# /etc/puppetlabs/puppet/hiera.yaml
...
hierarchy:
- "%{::clientcert}"
- common
# /etc/puppetlabs/puppet/hieradata/web01.example.com.yaml
---
classes:
- apache
- memcached
- wordpress
Bug note: In this version of Puppet, some uses of the contain function are aected by bug
PUP-1597. This bug prevents contain from accepting class names with an absolute ::
prex (for example, ::ntp::service).
This bug can also cause Error: undefined method 'ref' for nil:NilClass errors. These
occur when contain is given a class name that would have been aected by accidental
relative name lookup.
PUP-1597 will be xed in Puppet 3.7.
Puppet 3.6 Reference Manual Language: Classes 77/325
# /etc/puppetlabs/puppet/hieradata/common.yaml
---
classes:
- base::linux
# /etc/puppetlabs/puppet/manifests/site.pp
hiera_include(classes)
On the node web01.example.com, the example above would declare the classes apache, memcached,
wordpress, and base::linux. On other nodes, it would only declare base::linux.
The hiera_include function uses include-like behavior. (Multiple declarations OK; relies on
external data for parameters.) It accepts a single lookup key.
Using Resource-Like Declarations
Resource-like declarations look like normal resource declarations, using the special class pseudo-
resource type.
# Overriding a parameter:
class {'apache':
version => '2.2.21',
}
# Declaring a class with no parameters:
class {'base::linux':}
Resource-like declarations use resource-like behavior. (Multiple declarations prohibited;
parameters may be overridden at compile-time.) You can provide a value for any class parameter by
specifying it as resource attribute; any parameters not specied will follow the normal
external/default/fail lookup path.
In addition to class-specic parameters, you can also specify a value for any metaparameter. In
such cases, every resource contained in the class will also have that metaparameter:
# Cause the entire class to be noop:
class {'apache':
noop => true,
}
However, note that:
Any resource can specically override metaparameter values received from its container.
Metaparameters which can take more than one value (like the relationship metaparameters) will
merge the values from the container and any resource-specic values.
Puppet 3.6 Reference Manual Language: Classes 78/325
Assigning Classes From an ENC
Classes can also be assigned to nodes by external node classiersand LDAP node data. Note that
most ENCs assign classes with include-like behavior, and some ENCs assign them with resource-
like behaior. See the documentation of the ENC interface or the documentation of your specic ENC
for complete details.
class example ( $parameter_one = hiera('example::parameter_one'),
$parameter_two = hiera('example::parameter_two') ) {
...
}
class example (
$parameter_one = hiera('example::parameter_one',
$example::params::parameter_one),
$parameter_two = hiera('example::parameter_two',
$example::params::parameter_two)
Aside: Writing for Multiple Puppet Versions
Hiera integration and automatic parameter lookup were new features in Puppet 3; older
versions may install the Hiera functions as an add-on, but will not automatically nd
parameters. If you are writing code for multiple Puppet versions, you have several options:
Expect Users to Handle Parameters
The simplest approach is to not look back, and expect Puppet 2.x users to use resource-like
declarations. This isnt the friendliest approach, but many modules did this even before
auto-parameters were available, and users are accustomed to a subset of their modules
requiring it.
Use Hiera Functions in Default Values
If you are willing to require Hiera and the hiera-puppet add-on package for pre-3.0 users,
you can emulate Puppet 3s behavior by using a hiera function call in each parameters
default value:
Be sure to use 3.0-compatible lookup keys ( <class name>::<parameter>). This will let 2.x
users declare the class with include, and their Hiera data will continue to work without
changes once they upgrade to Puppet 3.
This approach can also be combined with the params class pattern, if default values are
necessary:
Puppet 3.6 Reference Manual Language: Classes 79/325
) inherits example::params { # Inherit the params class to let the
parameter list see its variables.
...
}
Appendix: Smart Parameter Defaults
This design pattern can make for signicantly cleaner code while enabling some really
sophisticated behavior around default values.
# /etc/puppet/modules/webserver/manifests/params.pp
class webserver::params {
$packages = $operatingsystem ? {
/(?i-mx:ubuntu|debian)/ => 'apache2',
/(?i-mx:centos|fedora|redhat)/ => 'httpd',
}
$vhost_dir = $operatingsystem ? {
/(?i-mx:ubuntu|debian)/ => '/etc/apache2/sites-enabled',
/(?i-mx:centos|fedora|redhat)/ => '/etc/httpd/conf.d',
}
}
# /etc/puppet/modules/webserver/manifests/init.pp
class webserver(
$packages = $webserver::params::packages,
$vhost_dir = $webserver::params::vhost_dir
) inherits webserver::params {
The drawbacks of this approach are:
It requires 2.x users to install Hiera and hiera-puppet.
Its slower on Puppet 3 if you dont set a value in your external data, Puppet will do two
searches before falling back to the default value.
However, depending on your needs, it can be a useful stopgap until all of your users are o
Puppet 2.7.
Avoid Class Parameters
Prior to Puppet 2.6, classes could only request data by reading arbitrary variables outside
their local scope. It is still possible to design classes like this. However, since dynamic scope
was removed in Puppet 3, old-style classes can only read top-scope or node-scope
variables, which makes them less exible than they were in previous versions. Your best
options for using old-style classes with Puppet 3 are to use an ENC to set your classes
variables, or to manually insert $special_variable = hiera('class::special_variable')
calls at top scope in your site manifest.
Puppet 3.6 Reference Manual Language: Classes 80/325
package { $packages: ensure => present }
file { 'vhost_dir':
path => $vhost_dir,
ensure => directory,
mode => '0750',
owner => 'www-data',
group => 'root',
}
}
To summarize whats happening here: When a class inherits from another class, it implicitly
declares the base class. Since the base classs local scope already exists before the new classs
parameters get declared, those parameters can be set based on information in the base class.
This is functionally equivalent to doing the following:
# /etc/puppet/modules/webserver/manifests/init.pp
class webserver( $packages = 'UNSET', $vhost_dir = 'UNSET' ) {
if $packages == 'UNSET' {
$real_packages = $operatingsystem ? {
/(?i-mx:ubuntu|debian)/ => 'apache2',
/(?i-mx:centos|fedora|redhat)/ => 'httpd',
}
}
else {
$real_packages = $packages
}
if $vhost_dir == 'UNSET' {
$real_vhost_dir = $operatingsystem ? {
/(?i-mx:ubuntu|debian)/ => '/etc/apache2/sites-enabled',
/(?i-mx:centos|fedora|redhat)/ => '/etc/httpd/conf.d',
}
}
else {
$real_vhost_dir = $vhost_dir
}
package { $real_packages: ensure => present }
file { 'vhost_dir':
path => $real_vhost_dir,
ensure => directory,
mode => '0750',
owner => 'www-data',
group => 'root',
}
}
Puppet 3.6 Reference Manual Language: Classes 81/325
but its a signicant readability win, especially if the amount of logic or the number of
parameters gets any higher than whats shown in the example.
Language: Dened Resource Types
Dened resource types(also called dened typesor denes) are blocks of Puppet code that can be
evaluated multiple times with dierent parameters. Once dened, they act like a new resource type:
you can cause the block to be evaluated by declaring a resource of that new type.
Denes can be used as simple macros or as a lightweight way to develop fairly sophisticated
resource types.
Syntax
Dening a Type
# /etc/puppetlabs/puppet/modules/apache/manifests/vhost.pp
define apache::vhost ($port, $docroot, $servername = $title, $vhost_name =
'*') {
include apache # contains Package['httpd'] and Service['httpd']
include apache::params # contains common config settings
$vhost_dir = $apache::params::vhost_dir
file { "${vhost_dir}/${servername}.conf":
content => template('apache/vhost-default.conf.erb'),
# This template can access all of the parameters and variables from
above.
owner => 'www',
group => 'www',
mode => '644',
require => Package['httpd'],
notify => Service['httpd'],
}
}
This creates a new type called apache::vhost.
The general form of a type denition is:
The define keyword
The name of the dened type
An optional set of parameters, which consists of:
An opening parenthesis
A comma-separated list of parameters, each of which consists of:
A new variable name, including the $ prex
An optional equals sign and default value (any data type)
Puppet 3.6 Reference Manual Language: Dened Resource Types 82/325
An optional trailing comma after the last parameter
A closing parenthesis
An opening curly brace
A block of arbitrary Puppet code, which generally contains at least one resource declaration
A closing curly brace
The denition does not cause the code in the block to be added to the catalog; it only makes it
available. To execute the code, you must declare one or more resources of the dened type.
Declaring an Instance
Instances of a dened type (often just called resources) can be declared the same way a normal
resource is declared. (That is, with a type, title, and set of attribute/value pairs.)
The parameters used when dening the type become the attributes (without the $ prex) used
when declaring resources of that type. Parameters which have a default value are optional; if they
are left out of the declaration, the default will be used. Parameters without defaults must be
specied.
To declare a resource of the apache::vhost type from the example above:
apache::vhost {'homepages':
port => 8081,
docroot => '/var/www-testhost',
}
Behavior
If a dened type is present, you can declare resources of that type anywhere in your manifests. See
Location below for details.
Declaring a resource of the type will cause Puppet to re-evaluate the block of code in the denition,
using dierent values for the parameters.
Parameters and Attributes
Every parameter of a dened type can be used as a local variable inside the denition. These
variables are not set with normal assignment statements; instead, each instance of the dened type
uses its attributes to set them:
apache::vhost {'homepages':
port => 8081, # Becomes the value of $port
docroot => '/var/www-testhost', # Becomes the value of $docroot
}
Puppet 3.6 Reference Manual Language: Dened Resource Types 83/325
$title and $name
Every dened type gets two free parameters, which are always available and do not have to be
explicitly added to the denition:
$title is always set to the title of the instance. Since it is guaranteed to be unique for each
instance, it is useful when making sure that contained resources are unique. (See Resource
Uniqueness below.)
$name defaults to the value of $title, but users can optionally specify a dierent value when
they declare an instance. This is only useful for mimicking the behavior of a resource with a
namevar, which is usually unnecessary. If you are wondering whether to use $name or $title,
use $title.
Unlike the other parameters, the values of $title and $name are already available inside the
parameter list. This means you can use $title as the default value (or part of the default value) for
another attribute:
define apache::vhost ($port, $docroot, $servername = $title, $vhost_name =
'*') { ...
Resource Uniqueness
Since multiple instances of a dened type might be declared in your manifests, you must make sure
that every resource in the denition will be dierent in every instance.Failing to do this will result in
compilation failures with a duplicate resource declaration error.
You can make resources dierent across instances by making their titles and names/namevars
include the value of $title or another parameter.
file { "${vhost_dir}/${servername}.conf":
Since $title (and possibly other parameters) will be unique per instance, this ensures the
resources will be unique as well.
Containment
Every instance of a dened type contains all of its unique resources. This means any relationships
formed between the instance and another resource will be extended to every resource that makes
up the instance.
Metaparameters
The declaration of a dened type instance can include any metaparameter. If it does:
Every resource contained in the instance will also have that metaparameter. So if you declare a
Puppet 3.6 Reference Manual Language: Dened Resource Types 84/325
dened resource with noop => true, every resource contained in it will also have noop => true,
unless they specically override it. Metaparameters which can take more than one value (like the
relationship metaparameters) will merge the values from the container and any specic values
from the individual resource.
The value of the metaparameter can be used as a variable in the denition, as though it were a
normal parameter. (For example, in an instance declared with require => Class['ntp'], the
local value of $require would be Class['ntp'].)
Resource Defaults
Just like with a normal resource type, you can declare resource defaults for a dened type:
# /etc/puppetlabs/puppet/manifests/site.pp
Apache::Vhost {
port => 80,
}
In this example, every resource of the type would default to port 80 unless specically overridden.
Location
Dened types can (and should) be stored in modules. Puppet is automatically aware of any dened
types in a valid module and can autoload them by name. Denitions should be stored in the
manifests/ directory of a module with one denition per le and each lename should reect the
name of its type. See Module Fundamentals for more details.
You can also put type denitions in the site manifest. If you do so, they may be placed anywhere in
the le and are not parse-order dependent.
Type denitions may also be placed inside class denitions; however, this limits their availability to
that class and is not recommended for any purpose. This is not formally deprecated in this version
of Puppet, but may become so in a future release.
Naming
The characters allowed in a dened types name are listed here.
If the denition is stored in a module, its name must reect its place in the module with its
namespace. See Module Fundamentals for details.
Note that if a types name has one or more namespaces in it, each name segment must be
ASIDE: BEST PRACTICES
You should usually only load dened types from modules. Although the additional options
below this aside will work, they are not recommended.
Puppet 3.6 Reference Manual Language: Dened Resource Types 85/325
capitalized when writing a resource reference, collector, or resource default. (For example, a
reference to the vhost resource declared above would be Apache::Vhost['homepages'].)
Language: Containment of Resources
Containment
Classes and dened typeinstances contain the resources they declare. Any contained resources will
not be applied before the container is begun, and will be nished before the container is nished.
This eectively means that if any resource or class forms a relationship with the container, it will
form the same relationship with every resource inside the container.
class ntp {
file { '/etc/ntp.conf':
...
require => Package['ntp'],
notify => Service['ntp'],
}
service { 'ntp':
...
}
package { 'ntp':
...
}
}
include ntp
exec {'/usr/local/bin/update_custom_timestamps.sh':
require => Class['ntp'],
}
In this example, Exec['/usr/local/bin/update_custom_timestamps.sh'] would happen after
every resource in the ntp class, including the package, the le, and the service.
This feature also allows you to notify and subscribe to classes and dened resource types as
though they were a single resource.
Containing Resources
Resources of both native and dened resource types are automatically contained by the class or
dened type in which they are declared.
Containing Classes
Having classes contain other classes can be very useful, especially in larger modules where you
Puppet 3.6 Reference Manual Language: Containment of Resources 86/325
want to improve code readability by moving chunks of implementation into separate les.
However, unlike resources, Puppet does not automatically contain classes when they are declared
inside another class. This is because classes may be declared in several places via include and
similar functions. Most of these places shouldnt contain the class, and trying to contain it
everywhere would cause huge problems.
Instead, you must manually contain any classes that need to be contained.
The contain Function
Use the contain function when a class should be contained. The contain function will declare the
class with include-like behavior if it isnt already declared, and will cause it to be contained by the
surrounding class.
In an example NTP module where service conguration is moved out into its own class:
class ntp {
file { '/etc/ntp.conf':
...
require => Package['ntp'],
notify => Class['ntp::service'],
}
contain ntp::service
package { 'ntp':
...
}
}
include ntp
exec { '/usr/local/bin/update_custom_timestamps.sh':
require => Class['ntp'],
}
This will ensure that the exec will happen after all the resources in both class ntp and class
ntp::service. (If ntp::service had been declared with include instead of contain, the exec
would happen after the le and the package, but wouldnt necessarily happen after the service.)
To contain classes that are declared with the resource-like declaration syntax, use the contain
function after declaring the class:
class ntp {
# ...
class { 'ntp::service':
enable => true,
}
contain 'ntp::service'
# ...
}
Puppet 3.6 Reference Manual Language: Containment of Resources 87/325
Faux Containment (for Compatibility With Puppet 3.4.0)
Versions prior to Puppet 3.4.0 and Puppet Enterprise 3.2 do not ship with the contain function. To
support these versions, you must mimic containment with the anchor pattern.
To use the anchor pattern:
The containing class must include two uniquely-named anchor resources. (Anchor resources
dont have any eect on the target system, and only exist to form relationships with.)
Any contained classes must have relationships ensuring they happen after one anchor and
before the other.
In an example NTP module where service conguration is moved out into its own class:
class ntp {
file { '/etc/ntp.conf':
...
require => Package['ntp'],
notify => Class['ntp::service'],
}
include ntp::service
anchor { 'ntp_first': } -> Class['ntp::service'] -> anchor { 'ntp_last':
}
package { 'ntp':
...
}
}
include ntp
exec { '/usr/local/bin/update_custom_timestamps.sh':
require => Class['ntp'],
}
Bug note: In this version of Puppet, some uses of the contain function are aected by bug
PUP-1597. This bug prevents contain from accepting class names with an absolute ::
prex (for example, ::ntp::service).
This bug can also cause Error: undefined method 'ref' for nil:NilClass errors. These
occur when contain is given a class name that would have been aected by accidental
relative name lookup.
PUP-1597 will be xed in Puppet 3.7.
Note: To use the anchor pattern, the puppetlabs/stdlib module must be installed. This
module includes the dummy anchor resource type.
Puppet 3.6 Reference Manual Language: Containment of Resources 88/325
In this case, the ntp::service class still isnt technically contained, but any resource can safely
form a relationship with the ntp class and be assured that the relationship will propagate into all
relevant resources.
Language: Namespaces and Autoloading
Class and dened typenames may be broken up into segments called namespaces. Namespaces tell
the autoloader how to nd the class or dened type in your modules.
Syntax
Puppet class and dened typenames may consist of any number of namespace segments separated
by the :: (double colon) namespace separator. (This separator is analogous to the / [slash] in a le
path.)
class apache { ... }
class apache::mod { ... }
class apache::mod::passenger { ... }
define apache::vhost { ... }
Optionally, class/dene names can begin with the top namespace, which is the empty string. The
following names are equivalent:
apache and ::apache
apache::mod and ::apache::mod
etc.
This is ugly and should be unnecessary, but is occasionally required due to an outstanding design
issue. See below for details.
Autoloader Behavior
When a class or dened resource is declared, Puppet will use its full name to nd the class or
dened type in your modules. Names are interpreted as follows:
The rst segment in a name (excluding the empty top namespace) identies the module. Every
Important note: Earlier versions of Puppet used namespaces to navigate nested class/type
denitions, and the code that resolves names still behaves as though this were their primary
use. This can sometimes result in the wrong class being loaded. This is a major outstanding
design issue (PUP-121). See below for a full description of the issue.
Puppet 3.6 Reference Manual Language: Namespaces and Autoloading 89/325
class and dened type should be in its own le in the modules manifests directory, and each
le should have the .pp le extension.
If there are no additional namespaces, Puppet will look for the class or dened type in the
modules init.pp le.
Otherwise, Puppet will treat the nal segment as the le name and any interior segments as a
series of subdirectories under the manifests directory.
Thus, every class or dened type name maps directly to a le path within Puppets modulepath:
name le path
apache <modulepath>/apache/manifests/init.pp
apache::mod <modulepath>/apache/manifests/mod.pp
apache::mod::passenger <modulepath>/apache/manifests/mod/passenger.pp
Note again that init.pp always contains a class or dened type named after the module, and any
other .pp le contains a class or type with at least two namespace segments. (That is, apache.pp
would contain a class named apache::apache.)
Relative Name Lookup and Incorrect Name Resolution
In this version of Puppet, class name resolution is partially broken if the nal namespace
segment of a class in one module matches the name of another module, Puppet will sometimes
load the wrong class.
class bar {
notice("From class bar")
}
class foo::bar {
notice("From class foo::bar")
}
class foo {
include bar
}
include foo
In the example above, the invocation of include bar will actually declare class foo::bar. This is
because Puppet assumes class and dened type names are relative until proven otherwise. This is a
major outstanding design issue (PUP-121) which will not be resolved in Puppet 3, as the x will
break some amount of existing code.
Behavior
When asked to load a class or dened type foo, Puppet will:
Puppet 3.6 Reference Manual Language: Namespaces and Autoloading 90/325
Attempt to load <current namespace>::foo
If that fails, attempt to load <parent of current namespace>::foo
If that fails, continue searching for foo through every ancestor namespace
Finally, attempt to load foo from the top namespace (AKA ::foo)
A concrete example:
class apache::nagios {
include nagios
...
}
When asked to include nagios, Puppet will rst attempt to load apache::nagios::nagios. Since
that class does not exist, it will then attempt to load apache::nagios. This exists, and since the
include function can safely declare a class multiple times, Puppet does not complain. It will not
attempt to load class nagios from the nagios module.
Workaround
If a class within another module is blocking the declaration of a top-namespace class, you can force
the correct class to load by specifying its name from the top namespace (as seen above). To specify
a name from the top namespace, prepend :: (double colon) to it:
class apache::nagios {
include ::nagios # Start searching from the top namespace instead of the
local namespace
...
}
In the example above, Puppet will load class nagios from the nagios module instead of declaring
apache::nagios a second time.
Aside: Historical Context
Relative name lookup was introduced in pre-module versions of Puppet. It reects an
outdated assumption about how modules would be used.
PROTO-MODULES
Before modules were introduced, users would create module-like blobs by putting a group
of related classes and dened types into one manifest le, then using an import statement in
site.pp to make the group available to the parser.
Puppet 3.6 Reference Manual Language: Namespaces and Autoloading 91/325
# /etc/puppet/manifests/apache.pp
class apache { ... } # Manage Apache
class ssl { ... } # Optional SSL support for Apache
class python { ... } # Optional mod_python support for Apache
define vhost ($port) { ... } # Create an Apache vhost
# /etc/puppet/manifests/site.pp
import apache.pp
include apache
include ssl
class apache {
...
class ssl { ... }
class python { ... }
define vhost ($port) { ... }
}
NAMESPACING FOR REDISTRIBUTION
As proto-modules got more sophisticated, their authors wanted to share them with other
users. The problem with this is visible above: many modules were likely to have a python or
ssl class, and the lighttpd module probably had a vhost dene that clashed with the
Apache one.
The solution was namespacing, which would allow dierent proto-modules to use common
class and dened type names without competing for global identiers.
PRIVATE VS. PUBLIC
The implementation of namespaces relied on an assumption that turned out to be incorrect:
that classes and dened types other than the modules main class would (and should) mostly
be used inside the module, rather than applied directly to nodes. (That is, they would be
private, much like local variables.) Thus, namespacing was done by hiding denitions within
other denitions:
The short names of the internal classes and dened types could only be used inside the main
class. However, much like qualied variables, you could access them from anywhere by using
their full (that is, namespaced) name. Full names were constructed by prepending the full
name of the outer class, along with the :: namespace separator. (That is, the full name of
ssl would be apache::ssl, python would be apache::python, etc.)
This was the origin of the relative name lookup behavior, as Puppet assumed that a class that
had its own private python class would want to use that instead of the top-namespace
python class.
Puppet 3.6 Reference Manual Language: Namespaces and Autoloading 92/325
Language: Resource Collectors
Resource collectors (AKA the spaceship operator) select a group of resources by searching the
attributes of every resource in the catalog. This search is parse-order independent (that is, it even
includes resources which havent yet been declared at the time the collector is written). Collectors
realize virtual resources, can be used in chaining statements, and can override resource attributes.
Collectors have an irregular syntax that lets them function as both a statement and a value.
Syntax
User <| title == 'luke' |> # Will collect a single user resource whose
title is 'luke'
User <| groups == 'admin' |> # Will collect any user resource whose list of
supplemental groups includes 'admin'
Yumrepo['custom_packages'] -> Package <| tag == 'custom' |> # Will create
an order relationship with several package resources
The general form of a resource collector is:
The resource type, capitalized
<| An opening angle bracket (less-than sign) and pipe character
Optionally, a search expression (see below)
|> A pipe character and closing angle bracket (greater-than sign)
THIS TURNED OUT TO BE POINTLESS
Users and developers eventually realized several things about this arrangement:
Using a classs full name everywhere was actually not that big a deal and was in fact a lot
clearer and easier to read and maintain.
Public classes and dened types were more common than private ones and optimizing for
the less common case was an odd approach.
Even for classes and dened types that were only used within their module, there was little
real benet to be gained by making them private, since they were eectively public via
their full name anyway.
Those realizations led to the superior module autoloader design used today, where a classs
full name is eectively its only name. However, the previous name lookup behavior was
never deprecated or removed, for fear of breaking large amounts of existing code. This
leaves it present in Puppet 3, where it often annoys users who have adopted the modern
code style.
We plan to x this in a future release.
Puppet 3.6 Reference Manual Language: Resource Collectors 93/325
Note that exported resource collectors have a slightly dierent syntax; see below.
Search Expressions
Collectors can search the values of resource titles and attributes using a special expression syntax.
This resembles the normal syntax for Puppet expressions, but is not the same.
A collector with an empty search expression will match every resource of the specied type.
Parentheses may be used to improve readability. You can create arbitrarily complex expressions
using the following four operators:
==
!=
and
or
== (EQUALITY SEARCH)
This operator is non-transitive:
The left operand (attribute) must be the name of a resource attribute or the word title (which
searches on the resources title).
The right operand (search key) must be a string, boolean, number, resource reference, or undef.
The behavior of arrays and hashes in the right operand is undenedin this version of Puppet.
For a given resource, this operator will match if the value of the attribute (or one of the values
members, if the value is an array) is identical to the search key.
!= (NON-EQUALITY SEARCH)
This operator is non-transitive:
The left operand (attribute) must be the name of a resource attribute or the word title (which
searches on the resources title).
The right operand (search key) must be a string, boolean, number, resource reference, or undef.
The behavior of arrays and hashes in the right operand is undenedin this version of Puppet.
For a given resource, this operator will match if the value of the attribute is not identical to the
Note: Collectors can only search on attributes which are present in the manifests and cannot
read the state of the target system. For example, the collector Package <| provider == yum
|> would only collect packages whose provider attribute had been explicitly set to yum in
the manifests. It would not match any packages that would default to the yum provider based
on the state of the target system.
Puppet 3.6 Reference Manual Language: Resource Collectors 94/325
search key.
AND
Both operands must be valid search expressions.
For a given resource, this operator will match if both of the operands would match for that
resource.
OR
Both operands must be valid search expressions.
For a given resource, this operator will match if either of the operands would match for that
resource.
Location
Resource collectors may be used as independent statements, as the operand of a chaining
statement, or in a collector attribute block for amending resource attributes.
Notably, collectors cannot be used as the value of a resource attribute, the argument of a function,
or the operand of an expression.
Behavior
A resource collector will always realize any virtual resources that match its search expression. Note
that empty search expressions match every resource of the specied type.
In addition to realizing, collectors can function as a value in two places:
When used in a chaining statement, a collector will act as a proxy for every resource (virtual or
non) that matches its search expression.
When given a block of attributes and values, a collector will set and override those attributes for
every resource (virtual or not) that matches its search expression.
Note again that collectors used as values will also realize any matching virtual resources. If you use
virtualized resources, you must use care when chaining collectors or using them for overrides.
Exported Resource Collectors
An exported resource collector uses a modied syntax that realizes exported resources.
Syntax
Exported resource collectors are identical to collectors, except that their angle brackets are
Note: This operator will always match if the attributes value is an array. This behavior may be
undened.
Puppet 3.6 Reference Manual Language: Resource Collectors 95/325
doubled.
Nagios_service <<| |>> # realize all exported nagios_service resources
The general form of an exported resource collector is:
The resource type, capitalized
<<| Two opening angle brackets (less-than signs) and a pipe character
Optionally, a search expression (see above)
|>> A pipe character and two closing angle brackets (greater-than signs)
Behavior
Exported resource collectors exist only to import resources that were published by other nodes. To
use them, you need to have catalog storage and searching (storecongs) enabled. See Exported
Resources for more details. To enable exported resources, follow the installation instructions and
Puppet conguration instructionsin the PuppetDB manual.
Like normal collectors, exported resource collectors can be used with attribute blocks and chaining
statements.
Language: Node Denitions
A node denitionor node statement is a block of Puppet code that will only be included in one
nodes catalog. This feature allows you to assign specic congurations to specic nodes.
Node statements are an optional feature of Puppet. They can be replaced by or combined with an
external node classier, or you can eschew both and use conditional statements with facts to
classify nodes.
Unlike more general conditional structures, node statements only match nodes by name. By default,
the name of a node is its certname (which defaults to the nodes fully qualied domain name).
Location
Node denitions should go in the site manifest (site.pp).
Alternately, you can store node denitions in any number of manifest les which are imported into
site.pp:
# /etc/puppetlabs/puppet/manifests/site.pp
# Import every file in /etc/puppetlabs/puppet/manifests/nodes/
# (Usually, each file contains one node definition.)
Puppet 3.6 Reference Manual Language: Node Denitions 96/325
import 'nodes/*.pp'
# Import several nodes from a single file
import 'extra_nodes.pp'
This is one of the only recommended use cases for import. Note that using import will require you
to restart the puppet master if you change the node manifests and that importing many les will
slow down Puppets compilation time. See the documentation of import for details.
Syntax
# /etc/puppetlabs/puppet/manifests/site.pp
node 'www1.example.com' {
include common
include apache
include squid
}
node 'db1.example.com' {
include common
include mysql
}
In the example above, only www1.example.com would receive the apache and squid classes, and
only db1.example.com would receive the mysql class.
Node denitions look like class denitions. The general form of a node denition is:
The node keyword
The name(s) of the node(s)
Optionally, the inherits keyword followed by the name of another node denition
An opening curly brace
Any mixture of class declarations, variables, resource declarations, collectors, conditional
statements, chaining relationships, and functions
A closing curly brace
Node statements should never be put in modules. The behavior of a node statement in an
autoloaded manifest is undened.
ASIDE: BEST PRACTICES
Although node statements can contain almost any Puppet code, we recommend that you
only use them to set variables and declare classes. Avoid using resource declarations,
collectors, conditional statements, chaining relationships, and functions in them; all of these
Puppet 3.6 Reference Manual Language: Node Denitions 97/325
Naming
Node statements match nodes by name. A nodes name is its unique identier; by default, this is its
certname setting, which in turn resolves to the nodes fully qualied domain name.
A node statements name must be one of the following:
A quoted string
The bare word default
A regular expression
You may not create two node statements with the same name.
Multiple Names
You can use a comma-separated list of names to create a group of nodes with a single node
statement:
node 'www1.example.com', 'www2.example.com', 'www3.example.com' {
include common
include apache, squid
}
This example creates three identical nodes: www1.example.com, www2.example.com, and
www3.example.com.
The Default Node
The name default (without quotes) is a special value for node names. If no node statement
matching a given node can be found, the default node will be used. See Behavior below.
Regular Expression Names
belong in classes or dened types.
This will make it easier to switch between node denitions and an ENC.
NOTES ON NODE NAMES
The set of characters allowed in a node name is undenedin this version of Puppet. For
best future compatibility, you should limit node names to letters, numbers, periods,
underscores, and dashes.
Although it is possible to congure Puppet to use something other than the certname as a
node name, this is not generally recommended.
Puppet 3.6 Reference Manual Language: Node Denitions 98/325
Regular expressions (regexes) can be used as node names. This is another method for writing a
single node statement that matches multiple nodes.
node /^www\d+$/ {
include common
}
The above example would match www1, www13, and any other node whose name consisted of www
and one or more digits.
node /^(foo|bar)\.example\.com$/ {
include common
}
The above example would match foo.example.com and bar.example.com, but no other nodes.
Behavior
If site.pp contains at least one node denition, it must have one for every node; compilation for a
node will fail if one cannot be found. (Hence the usefulness of the default node.) If site.pp
contains no node denitions, this requirement is dropped.
Matching
A given node will only get the contents of one node denition, even if two node statements could
match a nodes name. Puppet will do the following checks in order when deciding which denition
to use:
Thus, for the node www01.example.com, Puppet would try the following, in order:
www01.example.com
The rst regex matching www01.example.com
Make sure that node regexes do not overlap. If more than one regex statement matches a
given node, the one it gets will be parse-order dependent.
1. If there is a node denition with the nodes exact name, Puppet will use it.
2. If there is at least one regular expression node statement that matches the nodes whole name,
Puppet will use the rst one it nds.
3. If the nodes name looks like a fully qualied domain name (i.e. multiple period-separated
groups of letters, numbers, underscores and dashes), Puppet will chop o the nal group and
start again at step 1. (That is, if a denition for www01.example.com isnt found, Puppet will look
for a denition matching www01.example.)
4. Puppet will use the default node.
Puppet 3.6 Reference Manual Language: Node Denitions 99/325
www01.example
The rst regex matching www01.example
www01
The rst regex matching www01
default
You can turn o this fuzzy name matching by changing the puppet masters
strict_hostname_checking setting to true. This will cause Puppet to skip step 3 and only use the
nodes full name before resorting to default.
Regex Capture Variables
Regex node denitions will set numbered regex capture variables ($1, $2, etc.) within the body of
the node denition. This is similar to the behavior of conditional statements that use regexes.
Code Outside Node Statements
Puppet code that is outside any node statement will be compiled for every node. That is, a given
node will get both the code in its node denition and the code outside any node denition.
Node Scope
Node denitions create a new anonymous scope that can override variables and defaults from top
scope. See the section on node scope for details.
Merging With ENC Data
Node denitions and external node classierscan co-exist. Puppet merges their data as follows:
Variables from an ENC are set at top scope and can thus be overridden by variables in a node
denition.
Classes from an ENC are declared at node scope, which means they will be aected by any
variables set in the node denition.
Although ENCs and node denitions can work together, we recommend that most users pick one or
the other.
Inheritance
Nodes can inherit from other nodes using the inherits keyword. Inheritance works identically to
class inheritance. This feature is not recommended; see the aside below.
Example:
node 'common' {
$ntpserver = 'time.example.com'
include common
Puppet 3.6 Reference Manual Language: Node Denitions 100/325
}
node 'www1.example.com' inherits 'common' {
include ntp
include apache
include squid
}
In the above example, www1.example.com would receive the common, ntp, apache, and squid
classes, and would have an $ntpserver of time.example.com.
node 'common' {
$ntpserver = 'time.example.com'
include common
include ntp
}
node 'www01.example.com' inherits 'common' {
# Override default NTP server:
$ntpserver = '0.pool.ntp.org'
}
ASIDE: BEST PRACTICES
You should almost certainly avoid using node inheritance. Many users attempt to do the
following:
This will have the opposite of the intended eect, because Puppet treats node denitions like
classes. It does not mash the two together and then compile the mix; instead, it compiles the
base class, then compiles the derived class, which gets a parent scope and special
permission to modify resource attributes from the base class.
In the example above, this means that by the time node www01.example.com has set its own
value for $ntpserver, the ntp class has already received the value it needed and is no longer
interested in that variable. For the derived node to override that variable for classes in the
base node, it would have to be complied before the base node, and there is no way for
Puppets current implementation to do that.
ALTERNATIVES TO NODE INHERITANCE
Most users who need hierarchical data should keep it in an external source and have their
manifests look it up. The best solution right now is Hiera, which is available by default in
Puppet 3 and later. See our Hiera guides for more information about using it.
ENCs can look up data from any arbitrary source, and return it to Puppet as top-scope
variables.
If you have node-specic data in an external CMDB, you can easily write custom Puppet
functions to query it.
For very small numbers of nodes, you can copy and paste to make complete node
Puppet 3.6 Reference Manual Language: Node Denitions 101/325
Language: Data Types
The Puppet language allows several data types as variables, attribute values, and function
arguments:
Booleans
The boolean type has two possible values: true and false. Literal booleans must be one of these
two bare words (that is, not quoted).
The condition of an if statement is a boolean value. All of Puppets comparison expressions
return boolean values, as do many functions.
Automatic Conversion to Boolean
If a non-boolean value is used where a boolean is required, it will be automatically converted to a
boolean as follows:
Strings
Empty strings are false; all other strings are true. That means the string "false" actually
resolves as true. Warning: all facts are strings in this version of Puppet, so boolean facts
must be handled carefully.
Numbers
All numbers are true, including zero and negative numbers.
Undef
The special data type undef is false.
Arrays and Hashes
denitions for special-case nodes.
With discipline, you can use node inheritance only for data lookup. The safest approach is
to only set variables in the base nodes, then declare all classes in the derived nodes. This
is less terse than the mix-and-match that most users try rst, but is completely reliable.
Note: the puppetlabs-stdlib module includes a str2bool function which converts
strings to boolean values more intelligently.
Note: the puppetlabs-stdlib module includes a num2bool function which converts
numbers to boolean values more intelligently.
Puppet 3.6 Reference Manual Language: Data Types 102/325
Any array or hash is true, including the empty array and empty hash.
Resource References
Any resource reference is true, regardless of whether or not the resource it refers to has
been evaluated, whether the resource exists, or whether the type is valid.
Regular expressions cannot be converted to boolean values.
Undef
Puppets special undef value is roughly equivalent to nil in Ruby; variables which have never been
declared have a value of undef. Literal undef values must be the bare word undef.
The undef value is usually useful for testing whether a variable has been set. It can also be used as
the value of a resource attribute, which can let you un-set any value inherited from a resource
default and cause the attribute to be unmanaged.
When used as a boolean, undef is false.
Strings
Strings are unstructured text fragments of any length. They may or may not be surrounded by
quotation marks. Use single quotes for all strings that do not require variable interpolation, and
double quotes for strings that do require variable interpolation.
Bare Words
Bare (that is, not quoted) words are usually treated as single-word strings. To be treated as a
string, a bare word must:
Not be a reserved word
Begin with a lower case letter, and contain only letters, digits, hyphens (-), and underscores (_).
Bare words that begin with upper case letters are interpreted as resource references.
Bare word strings are usually used with attributes that accept a limited number of one-word values,
such as ensure.
Single-Quoted Strings
Strings surrounded by single quotes 'like this' do not interpolate variables, and the only escape
sequences permitted are \' (a literal single quote) and \\ (a literal backslash). Line breaks within
the string are interpreted as literal line breaks.
Lone backslashes are literal backslashes, unless followed by a single quote or another backslash.
That is:
Puppet 3.6 Reference Manual Language: Data Types 103/325
When a backslash occurs at the very end of a single-quoted string, a double backslash must be
used instead of a single backslash. For example: path => 'C:\Program Files(x86)\\'
When a literal double backslash is intended, a quadruple backslash must be used.
Double-Quoted Strings
Strings surrounded by double quotes "like this" allow variable interpolation and several escape
sequences. Line breaks within the string are interpreted as literal line breaks, and you can also
insert line breaks by using the \n escape sequence.
VARIABLE INTERPOLATION
Any $variable in a double-quoted string will be replaced with its value. To remove ambiguity
about which text is part of the variable name, you can surround the variable name in curly braces:
path => "${apache::root}/${apache::vhostdir}/${name}",
EXPRESSION INTERPOLATION
In a double-quoted string, you may interpolate the value of an arbitrary expression (which may
contain both variables and literal values) by putting it inside ${} (a pair of curly braces preceded by
a dollar sign):
file {'config.yml':
content => "...
db_remote: ${ $clientcert !~ /^db\d+/ }
...",
ensure => file,
}
This is of limited use, since most expressions resolve to boolean or numerical values.
Behavioral oddities of interpolated expressions:
You may not use bare word strings or numbers; all literal string or number values must be
quoted. The behavior of bare words in an interpolated expression is undened.
Within the ${}, you may use double or single quotes without needing to escape them.
Interpolated expressions may not use function calls as operands.
ESCAPE SEQUENCES
The following escape sequences are available:
\$ literal dollar sign
Note: This is not recommended.
Puppet 3.6 Reference Manual Language: Data Types 104/325
\" literal double quote
\' literal single quote
\\ single backslash
\n newline
\r carriage return
\t tab
\s space
Line Breaks
Quoted strings may continue over multiple lines, and line breaks are preserved as a literal part of
the string.
Puppet does not attempt to convert line breaks, which means that the type of line break (Unix/LF or
Windows/CRLF) used in the le will be preserved. You can also insert literal foreign line breaks into
strings:
To insert a CRLF in a manifest le that uses Unix line endings, use the \r\n escape sequences in
a double-quoted string.
To insert an LF in a manifest that uses Windows line endings, use the \n escape sequence in a
double-quoted string.
Encoding
Puppet treats strings as sequences of bytes. It does not recognize encodings or translate between
them, and non-printing characters are preserved.
However, Puppet Labs recommends that all strings be valid UTF8. Future versions of Puppet may
impose restrictions on string encoding, and using only UTF8 will protect you in this event.
Additionally, PuppetDB will remove invalid UTF8 characters when storing catalogs.
Resource References
Resource references identify a specic existing Puppet resource by its type and title. Several
attributes, such as the relationship metaparameters, require resource references.
# A reference to a file resource:
subscribe => File['/etc/ntp.conf'],
...
# A type with a multi-segment name:
before => Concat::Fragment['apache_port_header'],
The general form of a resource reference is:
Puppet 3.6 Reference Manual Language: Data Types 105/325
The resource type, capitalized (every segment must be capitalized if the type includes a
namespace separator [ ::])
An opening square bracket
The title of the resource, or a comma-separated list of titles
A closing square bracket
Unlike variables, resource references are not parse-order dependent, and can be used before the
resource itself is declared.
Multi-Resource References
Resource references with an array of titles or comma-separated list of titles refer to multiple
resources of the same type:
# A multi-resource reference:
require => File['/etc/apache2/httpd.conf', '/etc/apache2/magic',
'/etc/apache2/mime.types'],
# An equivalent multi-resource reference:
$my_files = ['/etc/apache2/httpd.conf', '/etc/apache2/magic',
'/etc/apache2/mime.types']
require => File[$my_files]
They can be used wherever an array of references might be used. They can also go on either side of
a chaining arrow or receive a block of additional attributes.
Numbers
Puppets arithmetic expressions accept integers and oating point numbers. Internally, Puppet
treats numbers like strings until they are used in a numeric context.
Numbers can be written as bare words or quoted strings, and may consist only of digits with an
optional negative sign ( -) and decimal point.
$some_number = 8 * -7.992
$another_number = $some_number / 4
Numbers cannot include explicit positive signs ( +) or exponents. Numbers between -1 and 1
cannot start with a bare decimal point; they must have a leading zero.
$product = 8 * +4 # syntax error
$product = 8 * 4 # OK
$product = 8 * .12 # syntax error
$product = 8 * 0.12 # OK
Puppet 3.6 Reference Manual Language: Data Types 106/325
Arrays
Arrays are written as comma-separated lists of items surrounded by square brackets. An optional
trailing comma is allowed between the nal value and the closing square bracket.
[ 'one', 'two', 'three' ]
# Equivalent:
[ 'one', 'two', 'three', ]
The items in an array can be any data type, including hashes or more arrays.
Resource attributes which can optionally accept multiple values (including the relationship
metaparameters) expect those values in an array.
Indexing
You can access items in an array by their numerical index (counting from zero). Square brackets are
used for indexing.
Example:
$foo = [ 'one', 'two', 'three' ]
notice( $foo[1] )
This manifest would log two as a notice. ( $foo[0] would be one, since indexing counts from zero.)
Nested arrays and hashes can be accessed by chaining indexes:
$foo = [ 'one', {'second' => 'two', 'third' => 'three'} ]
notice( $foo[1]['third'] )
This manifest would log three as a notice. ( $foo[1] is a hash, and we access a key named
'third'.)
Arrays support negative indexing, with -1 being the nal element of the array:
$foo = [ 'one', 'two', 'three', 'four', 'five' ]
notice( $foo[2] )
notice( $foo[-2] )
The rst notice would log three, and the second would log four.
Additional Functions
The puppetlabs-stdlib module contains several additional functions for dealing with arrays,
Puppet 3.6 Reference Manual Language: Data Types 107/325
including:
delete
delete_at
flatten
grep
hash
is_array
join
member
prefix
range
reverse
shuffle
size
sort
unique
validate_array
values_at
zip
Hashes
Hashes are written as key/value pairs surrounded by curly braces; a key is separated from its value
by a => (arrow, fat comma, or hash rocket), and adjacent pairs are separated by commas. An
optional trailing comma is allowed between the nal value and the closing curly brace.
{ key1 => 'val1', key2 => 'val2' }
# Equivalent:
{ key1 => 'val1', key2 => 'val2', }
Hash keys are strings, but hash values can be any data type, including arrays or more hashes.
Indexing
You can access hash members with their key; square brackets are used for indexing.
$myhash = { key => "some value",
Puppet 3.6 Reference Manual Language: Data Types 108/325
$myhash = { key => "some value",
other_key => "some other value" }
notice( $myhash[key] )
This manifest would log some value as a notice.
Nested arrays and hashes can be accessed by chaining indexes:
$main_site = { port => { http => 80,
https => 443 },
vhost_name => 'docs.puppetlabs.com',
server_name => { mirror0 => 'warbler.example.com',
mirror1 => 'egret.example.com' }
}
notice ( $main_site[port][https] )
This example manifest would log 443 as a notice.
Additional Functions
The puppetlabs-stdlib module contains several additional functions for dealing with hashes,
including:
has_key
is_hash
keys
merge
validate_hash
values
Regular Expressions
Regular expressions (regexes) are Puppets one non-standard data type. They cannot be assigned
to variables, and they can only be used in the few places that specically accept regular
expressions. These places include: the =~ and !~ regex match operators, the cases in selectors and
case statements, and the names of node denitions. They cannot be passed to functions or used in
resource attributes. (Note that the regsubst function takes a stringied regex in order to get
around this.)
Regular expressions are written as standard Ruby regular expressions (valid for the version of Ruby
being used by Puppet) and must be surrounded by forward slashes:
if $host =~ /^www(\d+)\./ {
notify { "Welcome web server #$1": }
Puppet 3.6 Reference Manual Language: Data Types 109/325
}
Alternate forms of regex quoting are not allowed and Ruby-style variable interpolation is not
available.
Regex Options
Regexes in Puppet cannot have options or encodings appended after the nal slash. However, you
may turn options on or o for portions of the expression using the (?<ENABLED
OPTION>:<SUBPATTERN>) and (?-<DISABLED OPTION>:<SUBPATTERN>) notation. The following
example enables the i option while disabling the m and x options:
$packages = $operatingsystem ? {
/(?i-mx:ubuntu|debian)/ => 'apache2',
/(?i-mx:centos|fedora|redhat)/ => 'httpd',
}
The following options are allowed:
i Ignore case
m Treat a newline as a character matched by .
x Ignore whitespace and comments in the pattern
Regex Capture Variables
Within conditional statements that use regexes (but not node denitionsthat use them), any
captures from parentheses in the pattern will be available inside the associated value as numbered
variables ( $1, $2, etc.), and the entire match will be available as $0.
These are not normal variables, and have some special behaviors:
The values of the numbered variables do not persist outside the code block associated with the
pattern that set them.
In nested conditionals, each conditional has its own set of values for the set of numbered
variables. At the end of an interior statement, the numbered variables are reset to their previous
values for the remainder of the outside statement. (This causes conditional statements to act like
[local scopes][local], but only with regard to the numbered variables.)
Language: Comments
Puppet supports two types of comments:
Shell-Style Comments
Puppet 3.6 Reference Manual Language: Comments 110/325
Shell-style comments (also known as Ruby-style comments) begin with a hash symbol ( #) and
continue to the end of a line. They can start at the beginning of a line or partway through a line that
began with code.
# This is a comment
file {'/etc/ntp.conf': # This is another comment
ensure => file,
owner => root,
}
C-Style Comments
C-style comments are delimited by slashes with inner asterisks. They can span multiple lines. This
comment style is less frequently used than shell-style.
/*
this is a comment
*/
Language: Virtual Resources
A virtual resource declaration species a desired state for a resource without adding it to the
catalog. You can then add the resource to the catalog by realizing it elsewhere in your manifests.
This splits the work done by a normal resource declaration into two steps.
Although virtual resources can only be declared once, they can be realized any number of times
(much as a class may be included multiple times).
Purpose
Virtual resources are useful for:
Resources whose management depends on at least one of multiple conditions being met
Overlapping sets of resources which may be required by any number of classes
Resources which should only be managed if multiple cross-class conditions are met
Virtual resources can be used in some of the same situations as classes, since they both oer a safe
way to add a resource to the catalog in more than one place. The features that distinguish virtual
resources are:
Searchability via resource collectors, which lets you realize overlapping clumps of virtual
resources
Flatness, such that you can declare a virtual resource and realize it a few lines later without
Puppet 3.6 Reference Manual Language: Virtual Resources 111/325
having to clutter your modules with many single-resource classes
For more details, see Virtual Resource Design Patterns.
Syntax
Virtual resources are used in two steps: declaring and realizing.
# <modulepath>/apache/manifests/init.pp
...
# Declare:
@a2mod { 'rewrite':
ensure => present,
} # note: The a2mod type is from the puppetlabs-apache module.
# <modulepath>/wordpress/manifests/init.pp
...
# Realize:
realize A2mod['rewrite']
# <modulepath>/freight/manifests/init.pp
...
# Realize again:
realize A2mod['rewrite']
In the example above, the apache class declares a virtual resource, and both the wordpress and
freight classes realize it. The resource will be managed on any node that has the wordpress
and/or freight classes applied to it.
Declaring a Virtual Resource
To declare a virtual resource, prepend @ (the at sign) to the type of a normal resource declaration:
@user {'deploy':
uid => 2004,
comment => 'Deployment User',
group => www-data,
groups => ["enterprise"],
tag => [deploy, web],
}
Realizing With the realize Function
To realize one or more virtual resources by title, use the realize function, which accepts one or
more resource references:
realize User['deploy'], User['zleslie']
Puppet 3.6 Reference Manual Language: Virtual Resources 112/325
The realize function may be used multiple times on the same virtual resource and the resource
will only be added to the catalog once.
Realizing With a Collector
Any resource collector will realize any virtual resource that matches its search expression:
User <| tag == web |>
You can use multiple resource collectors that match a given virtual resource and it will only be
added to the catalog once.
Note that a collector used in an override block or a chaining statement will also realize any
matching virtual resources.
Behavior
By itself, a virtual resource declaration will not add any resources to the catalog. Instead, it makes
the virtual resource available to the compiler, which may or may not realize it. A matching resource
collector or a call to the realize function will cause the compiler to add the resource to the
catalog.
Parse-Order Independence
Virtual resources do not depend on parse order. You may realize a virtual resource before the
resource has been declared.
Collectors vs. the realize Function
The realize function will cause a compilation failure if you attempt to realize a virtual resource
that has not been declared. Resource collectors will fail silently if they do not match any resources.
Virtual Resources in Classes
If a virtual resource is contained in a class, it cannot be realized unless the class is declared at some
point during the compilation. A common pattern is to declare a class full of virtual resources and
then use a collector to choose the set of resources you need:
include virtual::users
User <| groups == admin or group == wheel |>
Dened Resource Types
You may declare virtual resources of dened resource types. This will cause every resource
contained in the dened resource to behave virtually they will not be added to the catalog unless
the dened resource is realized.
Puppet 3.6 Reference Manual Language: Virtual Resources 113/325
Run Stages
Virtual resources will be evaluated in the run stage in which they are declared, not the run stage in
which they are realized.
Language: Exported Resources
An exported resource declaration species a desired state for a resource, does not manage the
resource on the target system, and publishes the resource for use by other nodes. Any node
(including the node that exported it) can then collect the exported resource and manage its own
copy of it.
Purpose
Exported resources allow nodes to share information with each other. This is useful when one node
has information that another node needs in order to manage a resource the node with the
information can construct and publish the resource, and the node managing the resource can
collect it.
The most common use cases are monitoring and backups. A class that manages a service like
PostgreSQL can export a nagios_service resource describing how to monitor the service,
including information like its hostname and port. The Nagios server can then collect every
nagios_service resource, and will automatically start monitoring the Postgres server.
For more details, see Exported Resource Design Patterns.
Syntax
Using exported resources requires two steps: declaring and collecting.
class ssh {
# Declare:
Note: Exported resources require catalog storage and searching (formerly known as
storecongs) to be enabled on your puppet master. Both the catalog storage and the
searching (among other features) are provided by PuppetDB. To enable exported resources,
follow these instructions:
Install PuppetDB on a server at your site
Connect your puppet master to PuppetDB
(Exported resources can also be enabled by the deprecated active_record storecongs
backend. However, all new users should avoid that and use PuppetDB instead.)
Puppet 3.6 Reference Manual Language: Exported Resources 114/325
@@sshkey { $hostname:
type => dsa,
key => $sshdsakey,
}
# Collect:
Sshkey <<| |>>
}
In the example above, every node with the ssh class will export its own SSH host key and then
collect the SSH host key of every node (including its own). This will cause every node in the site to
trust SSH connections from every other node.
Declaring an Exported Resource
To declare an exported resource, prepend @@ (a double at sign) to the type of a standard
resource declaration:
@@nagios_service { "check_zfs${hostname}":
use => 'generic-service',
host_name => "$fqdn",
check_command => 'check_nrpe_1arg!check_zfs',
service_description => "check_zfs${hostname}",
target => '/etc/nagios3/conf.d/nagios_service.cfg',
notify => Service[$nagios::params::nagios_service],
}
Collecting Exported Resources
To collect exported resources you must use an exported resource collector :
Nagios_service <<| |>> # Collect all exported nagios_service resources
# Collect exported file fragments for building a Bacula config file:
Concat::Fragment <<| tag == "bacula-storage-dir-${bacula_director}" |>>
(The second example, taken from puppetlabs-bacula, uses the concat module.)
Since any node could be exporting a resource, it is dicult to predict what the title of an exported
resource will be. As such, its usually best to search on a more general attribute. This is one of the
main use cases for tags.
See Exported Resource Collectors for more detail on the collector syntax and search expressions.
Behavior
When catalog storage and searching (AKA storecongs) are enabled, the puppet master will send a
copy of every catalog it compiles to PuppetDB. PuppetDB retains the most recent catalog for every
node and provides the puppet master with a search interface to those catalogs.
Puppet 3.6 Reference Manual Language: Exported Resources 115/325
Declaring an exported resource causes that resource to be added to the catalog and marked with
an exported ag, which prevents puppet agent from managing the resource (unless it was
collected). When PuppetDB receives the catalog, it also takes note of this ag.
Collecting an exported resource causes the puppet master to send a search query to PuppetDB.
PuppetDB will respond with every exported resource that matches the search expression, and the
puppet master will add those resources to the catalog.
Timing
An exported resource becomes available to other nodes as soon as PuppetDB nishes storing the
catalog that contains it. This is a multi-step process and may not happen immediately:
The puppet master must have compiled a given nodes catalog at least once before its resources
become available.
When the puppet master submits a catalog to PuppetDB, it is added to a queue and stored as
soon as possible. Depending on the PuppetDB servers workload, there may be a slight delay
between a nodes catalog being compiled and its resources becoming available.
Uniqueness
Every exported resource must be globally unique across every single node. If two nodes export
resources with the same title or same name/namevar and you attempt to collect both, the
compilation will fail. (Note: Some pre-1.0 versions of PuppetDB will not fail in this case. This is a
bug.)
To ensure uniqueness, every resource you export should include a substring unique to the node
exporting it into its title and name/namevar. The most expedient way is to use the hostname or
fqdn facts.
Exported Resource Collectors
Exported resource collectors do not collect normal or virtual resources. In particular, they cannot
retrieve non-exported resources from other nodes catalogs.
Language: Tags
Resources, classes, and dened type instancesmay have any number of tags associated with them,
plus they receive some tags automatically. Tags are useful for:
Collecting resources
Analyzing reports
Restricting catalog runs
Tag Names
Puppet 3.6 Reference Manual Language: Tags 116/325
See here for the characters allowed in tag names.
Assigning Tags to Resources
A resource may have any number of tags. There are several ways to assign a tag to a resource.
Automatic Tagging
Every resource automatically receives the following tags:
Its resource type
The full name of the class and/or dened typein which the resource was declared
Every namespace segment of the resources class and/or dened type
For example, a le resource in class apache::ssl would get the tags file, apache::ssl, apache,
and ssl.
Class tags are generally the most useful, especially when setting up tagmail or testing refactored
manifests.
Containment
Like relationships and most metaparameters, tags are passed along by containment. This means a
resource will receive all of the tags from the class and/or dened type that contains it. In the case of
nested containment (e.g. a class that declares a dened resource, or a dened type that declares
other dened resources), a resource will receive tags from all of its containers.
The tag Metaparameter
You can use the tag metaparameter in a resource declaration to add any number of tags:
apache::vhost {'docs.puppetlabs.com':
port => 80,
tag => ['us_mirror1', 'us_mirror2'],
}
The tag metaparameter can accept a single tag or an array. These will be added to the tags the
resource already has. Also, tag can be used with normal resources, dened resources, and classes
(when using the resource-like declaration syntax). Since containment applies to tags, the example
above would assign the us_mirror1 and us_mirror2 tags to every resource contained by
Apache::Vhost['docs.puppetlabs.com'].
The tag Function
You can use the tag function inside a class denition or dened type to assign tags to the
surrounding container and all of the resources it contains:
Puppet 3.6 Reference Manual Language: Tags 117/325
class role::public_web {
tag 'us_mirror1', 'us_mirror2'
apache::vhost {'docs.puppetlabs.com':
port => 80,
}
ssh::allowgroup {'www-data': }
@@nagios::website {'docs.puppetlabs.com': }
}
The example above would assign the us_mirror1 and us_mirror2 tags to all of the dened
resources being declared in the class role::public_web, as well as to all of the resources each of
them contains.
Using Tags
Collecting Resources
Tags can be used as an attribute in the search expression of a resource collector. This is mostly
useful for realizing virtual and exported resources.
Restricting Catalog Runs
Puppet agent and puppet apply can use the tags setting to only apply a subset of the nodes
catalog. This is useful when refactoring modules, and allows you to only apply a single class on a
test node.
The tags setting can be set in puppet.conf (to permanently restrict the catalog) or on the
command line (to temporarily restrict it):
$ sudo puppet agent --test --tags apache,us_mirror1
The value of the tags setting should be a comma-separated list of tags (with no spaces between
tags).
Sending Tagmail Reports
The built-in tagmail report handler can send emails to arbitrary email addresses whenever
resources with certain tags are changed. See the following for more info:
The tagmail report handler
The tagmail.conf le
Reading Tags in Custom Report Handlers
Resource tags are available to custom report handlers and out-of-band report processors: Each
Puppet 3.6 Reference Manual Language: Tags 118/325
Puppet::Resource::Status object and Puppet::Util::Log object has a tags key whose value is
an array containing every tag for the resource in question. See the following pages for more info:
Processing Reports
Report Format
Language: Run Stages
Run stages are an additional way to order resources. They allow groups of classes to run before or
after nearly everything else, without having to explicitly create relationships with every other class.
Run stages were added in Puppet 2.6.0.
Run stages have several major limitations; you should understand these before attempting to use
them.
The run stage feature has two parts:
A stage resource type.
A stage metaparameter, which assigns a class to a named run stage.
The Default main Stage
By default there is only one stage (named main). All resources are automatically associated with
this stage unless explicitly assigned to a dierent one. If you do not use run stages, every resource
is in the main stage.
Custom Stages
Additional stages are declared as normal resources. Each additional stage must have an order
relationship with another stage, such as Stage['main']. As with normal resources, these
relationships can be specied with metaparameters or with chaining arrows.
stage { 'first':
before => Stage['main'],
}
stage { 'last': }
Stage['main'] -> Stage['last']
In the above example, all classes assigned to the first stage will be applied before the classes
associated with the main stage and both stages will be applied before the last stage.
Assigning Classes to Stages
Puppet 3.6 Reference Manual Language: Run Stages 119/325
Once stages have been declared, a class may be assigned to a custom stage with the stage
metaparameter.
class { 'apt-keys':
stage => first,
}
The above example will ensure that the apt-keys class happens before all other classes, which can
be useful if most of your package resources rely on those keys.
In order to assign a class to a stage, you must use the resource-like class declaration syntax. You
cannot assign classes to stages with the include function.
Limitations and Known Issues
You cannot assign a class to a run stage when declaring it with include.
You cannot subscribe to or notify resources across a stage boundary.
Classes that contain other classes (with either the contain function or the anchor pattern) can
sometimes behave badly if declared with a run stage if the contained class is only declared by
its container, it will work ne, but if it is also declared anywhere outside its container, it will often
create a dependency cycle that will prevent the involved classes from being applied.
Due to these limitations, stages should only be used with the simplest of classes, and only when
absolutely necessary. Mass dependencies like package repositories are eectively the only valid use
case.
Language: Importing Manifests
Puppets normal behavior is to compile a single manifest (the site manifest) and autoload any
referenced classes from modules (optionally doing the same with a list of classes from an ENC).
The import keyword causes Puppet to compile more than one manifest without autoloading from
modules.
Deprecation Notice
The import keyword is deprecated. Using it will cause deprecation warnings to be logged on
the puppet master, and we plan to remove import completely in Puppet 4.
What to Use Instead
New users should avoid the import keyword, and existing users should stop using it.
Puppet 3.6 Reference Manual Language: Importing Manifests 120/325
Syntax
# /etc/puppetlabs/puppet/manifests/site.pp
# import many manifest files with node definitions
import 'nodes/*.pp'
# import a single manifest file with node definitions
import 'nodes.pp'
An import statement consists of the import keyword, followed by a literal quoted string with no
variable interpolation.
The string provided must be a le path or le glob (as implemented by Rubys Dir.glob method).
These paths must resolve to one or more Puppet manifest (.pp) les.
If the le path or glob is not fully qualied, it will be resolved relative to the manifest le in which
the import statement is found. Thus, the examples above assume that both the nodes/ directory
and the nodes.pp le are in the same /etc/puppetlabs/puppet/manifests directory as site.pp.
Behavior
Import statements have the following characteristics:
They read the contents of the requested le(s) and add their code to top scope
They are processed before any other code in the manifest is parsed
They cannot be contained by conditional structures or node/class denitions
These quirks mean the location of an import statement in a manifest does not matter. If an
uncommented import statement exists anywhere in a manifest, it will always run (even if it looks
like it shouldnt) and the code it imports will not be contained in any denition or conditional. The
following example illustrates this:
# /etc/puppetlabs/puppet/manifests/site.pp
node 'kestrel.example.com' {
import 'nodes/kestrel.pp'
}
Instead, do the following:
To keep your node denitionsin separate les, specify a directory as your main manifest.
To load classes and dened types, use modules.
Together, these two features replace import completely.
Puppet 3.6 Reference Manual Language: Importing Manifests 121/325
# /etc/puppetlabs/puppet/manifests/nodes/kestrel.pp
include ntp
include apache2
This import statement looks like it should insert code INTO the node denition that contains it;
instead, it will insert the code outside any node denition, and it will do so regardless of whether
the node denition matches the current node. The ntp and apache2 classes would be applied to
every node.
Implications and Best Practices
Due to the non-standard behavior of import, any imported le should only contain constructs like
node denitions and class denitions, which can exist at top scope without necessarily executing
on every node.
Interactions With the Autoloader
The behavior of import within autoloaded manifests is undened,and may vary randomly between
minor versions of Puppet. You should never place import statements in modules; they should only
exist in site.pp.
Inability to Reload
The puppet master service monitors its main site manifest and modules and will reload the les
whenever they are edited. However, because it only evaluates le globs when the parent le
containing them is reloaded, it cannot tell when imported manifests have been changed.
Thus, if you use import statements, you must manually cause your les to be reloaded whenever
you edit your imported manifests. You can do this by:
Restarting the puppet master
Editing (or touching) site.pp to trigger a reload
Module Fundamentals
Puppet 3.6 Reference Manual Module Fundamentals 122/325
Puppet Modules
Modules are self-contained bundles of code and data. You can write your own modules or you can
download pre-built modules from the Puppet Forge.
Nearly all Puppet manifests belong in modules. The sole exception is the main site.pp manifest,
which contains site-wide and node-specic code.
Every Puppet user should expect to write at least some of their own modules.
Continue reading to learn how to write and use Puppet modules.
See Installing Modules for how to install pre-built modules from the Puppet Forge.
See Publishing Modules for how to publish your modules to the Puppet Forge.
See Using Plugins for how to arrange plugins (like custom facts and custom resource types) in
modules and sync them to agent nodes.
See Documenting Modules for a README template and information on providing directions for
your module.
Using Modules
Modules are how Puppet nds the classes and types it can use it automatically loads any class or
dened typestored in its modules. Within a manifest or from an external node classier (ENC), any
of these classes or types can be declared by name:
# /etc/puppetlabs/puppet/site.pp
node default {
include apache
class {'ntp':
enable => false;
}
apache::vhost {'personal_site':
port => 80,
docroot => '/var/www/personal',
options => 'Indexes MultiViews',
}
}
Likewise, Puppet can automatically load plugins (like custom native resource types or custom facts)
from modules; see Using Plugins for more details.
To make a module available to Puppet, place it in one of the directories in Puppets modulepath.
You can easily install modules written by other users with the puppet module subcommand. See
Installing Modules for details.
Puppet 3.6 Reference Manual Puppet Modules 123/325
Module Layout
On disk, a module is simply a directory tree with a specic, predictable structure:
<MODULE NAME>
manifests
files
templates
lib
facts.d
tests
spec
Example
This example module, named my_module, shows the standard module layout in more detail:
my_module This outermost directorys name matches the name of the module.
manifests/ Contains all of the manifests in the module.
init.pp Contains a class denition. This classs name must match the modules name.
other_class.pp Contains a class named my_module::other_class.
my_defined_type.pp Contains a dened type named my_module::my_defined_type.
implementation/ This directorys name aects the class names beneath it.
foo.pp Contains a class named my_module::implementation::foo.
bar.pp Contains a class named my_module::implementation::bar.
files/ Contains static les, which managed nodes can download.
service.conf This les URL would be puppet:///modules/my_module/service.conf.
lib/ Contains plugins, like custom facts and custom resource types. These will be used by
both the puppet master server and the puppet agent service, and theyll be synced to all agent
nodes whenever they request their congurations. See Using Plugins for more details.
facts.d/ Contains external facts, which are an alternative to Ruby-based custom facts.
These will be synced to all agent nodes, so they can submit values for those facts to the
puppet master. (Requires Facter 2.0.1 or later.)
templates/ Contains templates, which the modules manifests can use. See Templates
for more details.
component.erb A manifest can render this template with
template('my_module/component.erb').
Puppet 3.6 Reference Manual Puppet Modules 124/325
tests/ Contains examples showing how to declare the modules classes and dened types.
init.pp
other_class.pp Each class or type should have an example in the tests directory.
spec/ Contains spec tests for any plugins in the lib directory.
Each of the modules subdirectories has a specic function, as follows.
Manifests
Each manifest in a modules manifests folder should contain one class or dened type.The le
names of manifests map predictably to the names of the classes and dened types they contain.
init.pp is special and always contains a class with the same name as the module.
Every other manifest contains a class or dened type named as follows:
Name of module :: Other directories:: (if any) Name of le (no extension)
my_module :: other_class
my_module :: implementation:: foo
Thus:
my_module::other_class would be in the le my_module/manifests/other_class.pp
my_module::implementation::foo would be in the le
my_module/manifests/implementation/foo.pp
The double colon that divides the sections of a classs name is called the namespace separator.
Allowed Module Names
Module names should only contain lowercase letters, numbers, and underscores, and should begin
with a lowercase letter; that is, they should match the expression [a-z][a-z0-9_]*. Note that these
are the same restrictions that apply to class names, but with the added restriction that module
names cannot contain the namespace separator ( ::) as modules cannot be nested.
Although some names that violate these restrictions currently work, using them is not
recommended.
Certain module names are disallowed:
main
settings
Files
Puppet 3.6 Reference Manual Puppet Modules 125/325
Files in a modules files directory are automatically served to agent nodes. They can be
downloaded by using puppet:/// URLs in the source attribute of a file resource.
Puppet URLs work transparently in both agent/master mode and standalone mode; in either case,
they will retrieve the correct le from a module.
Puppet URLs are formatted as follows:
Protocol 3 slashes Modules/ Name of module/ Name of le
puppet: /// modules/ my_module/ service.conf
So puppet:///modules/my_module/service.conf would map to my_module/files/service.conf.
Templates
Any ERB template (see Templates for more details) can be rendered in a manifest with the
template function. The output of the template is a simple string, which can be used as the content
attribute of a file resource or as the value of a variable.
The template function can look up templates identied by shorthand:
Template function ( Name of module/ Name of template )
template (' my_module/ component.erb ')
So template('my_module/component.erb') would render the template
my_module/templates/component.erb.
Writing Modules
To write a module, simply write classes and dened types and place them in properly named
manifest les as described above.
See here for more information on classes
See here for more information on dened types
Best Practices
The classes, dened types, and plugins in a module should all be related, and the module should
aim to be as self-contained as possible.
Manifests in one module should never reference les or templates stored in another module.
Be wary of having classes declare classes from other modules, as this makes modules harder to
redistribute. When possible, its best to isolate super-classes that declare many other classes in a
local site module.
Puppet 3.6 Reference Manual Puppet Modules 126/325
Plugins in Modules
Puppet 3.6 Reference Manual Plugins in Modules 127/325
Plugins in Modules
Learn how to distribute custom facts and types from the server to managed clients automatically.
Details
This page describes the deployment of custom facts and types for use by the client via modules.
Custom types and facts are stored in modules. These custom types and facts are then gathered
together and distributed via a le mount on your Puppet master called plugins.
This technique can also be used to bundle functions for use by the server when the manifest is
being compiled. Doing so is a two step process which is described further on in this document.
To enable module distribution you need to make changes on both the Puppet master and the
clients.
Module structure
Plugins are stored in the lib directory of a module, using an internal directory structure that
mirrors that of the Puppet code:
{modulepath}
{module}
lib
| augeas
lenses
facter
puppet
parser
functions
provider
| exec
| package
| etc... (any resource type)
type
As the directory tree suggests, custom facts should go in lib/facter/, custom types should go in
lib/puppet/type/, custom providers should go in lib/puppet/provider/{type}/, and custom
functions should go in lib/puppet/parser/functions/.
For example:
A custom user provider:
{modulepath}/{module}/lib/puppet/provider/user/custom_user.rb
Puppet 3.6 Reference Manual Plugins in Modules 128/325
A custom package provider:
{modulepath}/{module}/lib/puppet/provider/package/custom_pkg.rb
A custom type for bare Git repositories:
{modulepath}/{module}/lib/puppet/type/gitrepo.rb
A custom fact for the root of all home directories (that is, /home on Linux, /Users on Mac OS X,
etc.):
{modulepath}/{module}/lib/facter/homeroot.rb
A custom Augeas lens:
{modulepath}/{module}/lib/augeas/lenses/custom.aug
And so on.
Most types and facts should be stored in which ever module they are related to; for example, a Bind
fact might be distributed in your Bind module. If you wish to centrally deploy types and facts you
could create a separate module just for this purpose, for example one called custom.
So, if we are using our custom module and our modulepath is /etc/puppet/modules then types and
facts would be stored in the following directories:
/etc/puppet/modules/custom/lib/puppet/type
/etc/puppet/modules/custom/lib/puppet/provider
/etc/puppet/modules/custom/lib/puppet/parser/functions
/etc/puppet/modules/custom/lib/facter
Enabling Pluginsync
After setting up the directory structure, we then need to turn on pluginsync in our puppet.conf
conguration le on both the master and the clients:
[main]
pluginsync = true
Note: Support for syncing Augeas lenses was added in Puppet 2.7.18.
Puppet 3.6 Reference Manual Plugins in Modules 129/325
Note on Usage for Server Custom Functions
Functions are executed on the server while compiling the manifest. A module dened in the
manifest can include functions in the plugins directory. The custom function will need to be placed
in the proper location within the manifest rst:
{modulepath}/{module}/lib/puppet/parser/functions
Note that this location is not within the puppetmasters $libdir path. Placing the custom function
within the module plugins directory will not result in the puppetmasterd loading the new custom
function. The puppet client can be used to help deploy the custom function by copying it from
modulepath/module/lib/puppet/parser/functions to the proper $libdir location. To do so run the
puppet client on the server. When the client runs it will download the custom function from the
modules lib directory and deposit it within the correct location in $libdir. The next invocation of
the Puppet master by a client will autoload the custom function.
As always custom functions are loaded once by the Puppet master. Simply replacing a custom
function with a new version will not cause Puppet master to automatically reload the function. You
must restart the Puppet master.
Installing Modules
Puppet 3.6 Reference Manual Installing Modules 130/325
Installing Modules
Windows nodes that pull congurations from a Linux or Unix puppet master can use any Forge
modules installed on the master. Continue reading to learn how to use the module tool on your
puppet master.
On Windows nodes which compile their own catalogs, you can install a Forge module by
downloading and extracting the modules release tarball from the modules page on the Forge
(you will also need to download each module listed in the Dependencies tab). Then run the
following command in PowerShell or Command Prompt: puppet module install <path to
tarball> --ignore-dependencies.
Solaris Note To use the puppet module tool on Solaris systems, you must rst install gtar.
The Puppet Forge is a repository of pre-existing modules, written and contributed by users. These
modules solve a wide variety of problems so using them can save you time and eort.
The puppet module subcommand, which ships with Puppet, is a tool for nding and managing new
modules from the Forge. Its interface is similar to several common package managers, and makes it
easy to search for and install new modules from the command line.
Continue reading to learn how to install and manage modules from the Puppet Forge.
See Module Fundamentals to learn how to use and write Puppet modules.
See Publishing Modules to learn how to contribute your own modules to the Forge, including
information about the puppet module tools build and generate actions.
See Using Plugins for how to arrange plugins (like custom facts and custom resource types) in
modules and sync them to agent nodes.
See Documenting Modules for a README template and information on providing directions for
your module.
Using the Module Tool
The puppet module subcommand has several actions. The main actions used for managing
modules are:
install
Install a module from the Forge or a release archive.
# puppet module install puppetlabs-apache --version 0.0.2
list
List installed modules.
Puppet 3.6 Reference Manual Installing Modules 131/325
# puppet module list
search
Search the Forge for a module.
# puppet module search apache
uninstall
Uninstall a puppet module.
# puppet module uninstall puppetlabs-apache
upgrade
Upgrade a puppet module.
# puppet module upgrade puppetlabs-apache --version 0.0.3
If you have used a command line package manager tool (like gem, apt-get, or yum) before, these
actions will generally do what you expect. You can view a full description of each action with puppet
man module or by viewing the man page here.
Using the Module Tool Behind a Proxy
In order to use the puppet module tool behind a proxy, you need to set the following:
export http_proxy=http://10.187.255.9:8080
export https_proxy=http://10.187.255.9:8080
Alternatively, you can set these two proxy settings inside the user cong section in the
puppet.conf le: http_proxy_host and http_proxy_port. For more information, see
Conguration Reference.
Note: Make sure to set these two proxy settings in the user section only. Otherwise, there can be
adverse eects.
Installing Modules
The puppet module install action will install a module and all of its dependencies. By default, it
will install into the rst directory in Puppets modulepath.
Use the --version option to specify a version. You can use an exact version or a requirement
Puppet 3.6 Reference Manual Installing Modules 132/325
string like >=1.0.3.
Use the --force option to forcibly install a module or re-install an existing module.
Use the --environment option to install into a dierent environment.
Use the --modulepath option to manually specify which directory to install into. Note: To avoid
duplicating modules installed as dependencies, you may need to specify the modulepath as a list
of directories; see the documentation for setting the modulepath for details.
Use the --ignore-dependencies option to skip installing any modules required by this module.
Use the --debug option to see additional information about what the puppet module tool is
doing.
Installing From the Puppet Forge
To install a module from the Puppet Forge, simply identify the desired module by its full name. The
full name of a Forge module is formatted as username-modulename.
# puppet module install puppetlabs-apache
Installing From Another Module Repository
The module tool can install modules from other repositories that mimic the Forges interface. To do
this, change the module_repository setting in puppet.conf or specify a repository on the
command line with the --module_repository option. The value of this setting should be the base
URL of the repository; the default value, which uses the Forge, is http://forge.puppetlabs.com.
After setting the repository, follow the instructions above for installing from the Forge.
# puppet module install --module_repository http://dev-forge.example.com
puppetlabs-apache
Installing From a Release Tarball
To install a module from a release tarball, specify the path to the tarball instead of the module
name.
Make sure to use the --ignore-dependencies ag if you cannot currently reach the Puppet Forge
or are installing modules that have not yet been published to the Forge. This ag will tell the
puppet module tool not to try to resolve dependencies by connecting to the Forge. Be aware that in
this case you must manually install any dependencies.
# puppet module install ~/puppetlabs-apache-0.10.0.tar.gz --ignore-dependencies
Installing PE Supported Modules
Puppet 3.6 Reference Manual Installing Modules 133/325
PE 3.2 introduced supported modules, which includes additional elds in the modules
metadata.json le to indicate compatibility with PE versions and OSes. The puppet module tool
(PMT) has been updated to look for PE version requirements in the metadata.
If you are running PE 3.2 or greater, please note that if a version of the module matches the
installed version of PE, non-matching versions will be ltered out. The --force ag will prevent
this ltering, and will either install the most recent version of the module if no version is specied
or install the specied version. Note that the --force ag will ignore dependencies and checksums,
as well as overwrite installed modules with the same modulename. The --debug ag will show
whether a module is being ltered or not. If no PE version metadata is present in any version, all
available versions of the module will be displayed.
Note: It is possible that some community modules may also include this requirements metadata.
Finding Modules
Modules can be found by browsing the Forges web interface or by using the module tools search
action. The search action accepts a single search term and returns a list of modules whose names,
descriptions, or keywords match the search term.
$ puppet module search apache
Searching http://forge.puppetlabs.com ...
NAME DESCRIPTION AUTHOR KEYWORDS
puppetlabs-apache This is a generic ... @puppetlabs apache
web
puppetlabs-passenger Module to manage P... @puppetlabs apache
DavidSchmitt-apache Manages apache, mo... @DavidSchmitt apache
jamtur01-httpauth Puppet HTTP Authen... @jamtur01 apache
jamtur01-apachemodules Puppet Apache Modu... @jamtur01 apache
adobe-hadoop Puppet module to d... @adobe apache
adobe-hbase Puppet module to d... @adobe apache
adobe-zookeeper Puppet module to d... @adobe apache
adobe-highavailability Puppet module to c... @adobe apache
mon
adobe-mon Puppet module to d... @adobe apache
mon
puppetmanaged-webserver Apache webserver m... @puppetmanaged apache
ghoneycutt-apache Manages apache ser... @ghoneycutt apache
web
ghoneycutt-sites This module manage... @ghoneycutt apache
web
fliplap-apache_modules_sles11 Exactly the same a... @fliplap
mstanislav-puppet_yum Puppet 2. @mstanislav apache
mstanislav-apache_yum Puppet 2. @mstanislav apache
jonhadfield-wordpress Puppet module to s... @jonhadfield apache
php
saz-php Manage cli, apache... @saz apache
php
pmtacceptance-apache This is a dummy ap... @pmtacceptance apache
php
Puppet 3.6 Reference Manual Installing Modules 134/325
pmtacceptance-php This is a dummy ph... @pmtacceptance apache
php
Once youve identied the module you need, you can install it by name as described above.
Managing Modules
Listing Installed Modules
Use the module tools list action to see which modules you have installed (and which directory
theyre installed in).
Use the --tree option to view the modules arranged by dependency instead of by location on
disk.
Upgrading Modules
Use the module tools upgrade action to upgrade an installed module to the latest version. The
target module must be identied by its full name.
Use the --version option to specify a version.
Use the --ignore-dependencies option to skip upgrading any modules required by this module.
Uninstalling Modules
Use the module tools uninstall action to remove an installed module. The target module must be
identied by its full name:
# puppet module uninstall apache
Error: Could not uninstall module 'apache':
Module 'apache' is not installed
You may have meant `puppet module uninstall puppetlabs-apache`
# puppet module uninstall puppetlabs-apache
Removed /etc/puppet/modules/apache (v0.0.3)
By default, the tool wont uninstall a module which other modules depend on or whose les have
been edited since it was installed.
Use the --force option to uninstall even if the module is depended on or has been manually
edited.
Publishing Modules on the Puppet Forge
Puppet 3.6 Reference Manual Publishing Modules on the Puppet Forge 135/325
Publishing Modules on the Puppet Forge
The Puppet Forge is a community repository of modules, written and contributed by Puppet Open
Source and Puppet Enterprise users. Using the Puppet Forge is a great way to build on the work
others have done and get updates and expansions on your own module work. This document
describes how to publish your own modules to the Puppet Forge so that other users can install
them.
Continue reading to learn how to publish your modules to the Puppet Forge.
See Module Fundamentals for how to write and use your own Puppet modules.
See Installing Modules for how to install pre-built modules from the Puppet Forge.
See Using Plugins for how to arrange plugins (like custom facts and custom resource types) in
modules and sync them to agent nodes.
See Documenting Modules for a README template and information on providing directions for
your module.
Overview
This guide assumes that you have already written a useful Puppet module. To publish your module,
you will need to:
Note: As of Puppet 3.6 the Modulele has been deprecated in favor of the metadata.json le.
We strongly suggest that you use puppet module generate to create new modules, as it now
includes a dialog for creating your metadata.json. You can read more about how to deal with
your Modulelebelow.
1. Create a Puppet Forge account, if you dont already have one.
2. Prepare your module.
3. Write a metadata.json le with the required metadata.
4. Build an uploadable tarball of your module.
5. Upload your module using the Puppet Forges web interface.
A Note on Module Names
Because many users have published their own versions of modules with common names
(mysql, bacula, etc.), the Puppet Forge requires module names to have a username
prex. That is, if a user named puppetlabs maintained a mysql module, it would be
known to the Puppet Forge as puppetlabs-mysql.
Be sure to use this long name in your modules metadata.json le. However, you do not have
to rename the modules directory, and can leave the module in your active modulepath the
Puppet 3.6 Reference Manual Publishing Modules on the Puppet Forge 136/325
Create a Puppet Forge Account
Before you begin, you should create a user account on the Puppet Forge. You will need to know
your username when preparing to publish any of your modules.
Prepare the Module
If you already have a Puppet module with the correct directory layout, you may continue to the next
step.
Alternately, you can use the puppet module generate action to generate a template layout.
Generating a module will provide you with a sample README and a copy of the spec_helper tool
for writing rspec-puppet tests. It will also launch a series of questions that will create your
metadata.json le. If you decided to construct a module on your own rst, you will need to manually
copy that modules les into the generated module.
To generate a new module, run puppet module generate <USERNAME>-<MODULE NAME>. For
example:
build action will do the right thing as long as the metadata.json is correct.
Another Note on Module Names
Although the Puppet Forge expects to receive modules named username-module, its web
interface presents them as username/module. There isnt a good reason for this, and we are
working on reconciling the two; in the meantime, be sure to always use the username-
module style in your metadata les and when issuing commands.
1. Start by navigating to the Puppet Forge website and clicking the Sign Up link in the sidebar:
1. Fill in your details. After you nish, you will be asked to verify your email address via a
verication email. Once you have done so, you can publish modules to the Puppet Forge.
Puppet 3.6 Reference Manual Publishing Modules on the Puppet Forge 137/325
# puppet module generate examplecorp-mymodule
Generating module at /Users/Pat/Development/examplecorp-mymodule
examplecorp-mymodule
examplecorp-mymodule/manifests
examplecorp-mymodule/manifests/init.pp
examplecorp-mymodule/metadata.json
examplecorp-mymodule/Rakefile
examplecorp-mymodule/README
examplecorp-mymodule/spec
examplecorp-mymodule/spec/classes
examplecorp-mymodule/spec/classes/init_spec.rb
examplecorp-mymodule/spec/spec_helper.rb
examplecorp-mymodule/tests
examplecorp-mymodule/tests/init.pp
Write a metadata.json File
If you generated your module using the puppet module generate command, youll already have a
metadata.json le. If you put your module together without using the puppet module generate
command, you must make sure that you have a metadata.json le in your modules main directory.
The metadata.json is a JSON-formatted le containing information about your module, such as its
name, version, and dependencies.
Your metadata.json will look something like
{
"name" => "examplecorp-mymodule",
"version" => "0.0.1",
"author" => "Pat",
"license" => "Licensed under (Apache 2.0)",
"summary" => "A module for a thing",
"source" => "https://github.com/examplecorp/examplecorp-mymodule",
"project_page" => "(https://forge.puppetlabs.com/examplecorp/mymodule)",
"issues_url" => ""
}
The following elds make up a metadata.json le:
name REQUIRED. The full name of your module, including the username (e.g. username-
module see note above).
version REQUIRED. The current version of your module. This should be a semantic version.
author REQUIRED. The person who gets credit for creating the module. If not provided, this
eld will default to the username portion of the name eld.
license REQUIRED. The license under which your module is made available.
summary REQUIRED. A one-line description of your module.
Puppet 3.6 Reference Manual Publishing Modules on the Puppet Forge 138/325
source REQUIRED. The source repository for your module.
dependencies REQUIRED. A list of the other modules that your module depends on to
function. See Dependencies in metadata.json below for more details.
project_page Your modules website.
issues_url A link to your modules issue tracker.
Dependencies in metadata.json
If your modules functionality depends upon functionality in another module, you can express this
in the dependencies eld of your metadata.json le. The dependencies eld accepts an array of
hashes. Heres an example from the puppetlabs-postgresql module:
"dependencies": [ { "name": "puppetlabs/stdlib", "version_requirement": ">=3.2.0
<5.0.0" }, { "name": "puppetlabs/firewall", "version_requirement": ">= 0.0.4" }, {
"name": "puppetlabs/apt", "version_requirement": ">=1.1.0 <2.0.0" }, { "name":
"puppetlabs/concat", "version_requirement": ">= 1.0.0 <2.0.0" } ]
Note: Once youve generated your module and gone through the metadata.json dialog, you must
manually edit the metadata.json le to include the dependency information.
The version requirement in a dependency isnt limited to a single version; you can use several
operators for version comparisons.
1.2.3 A specic version.
>1.2.3 Greater than a specic version.
<1.2.3 Less than a specic version.
>=1.2.3 Greater than or equal to a specic version.
<=1.2.3 Less than or equal to a specic version.
>=1.0.0 <2.0.0 Range of versions; both conditions must be satised. (This example would
match 1.0.1 but not 2.0.1)
1.x A semantic major version. (This example would match 1.0.1 but not 2.0.1, and is
shorthand for >=1.0.0 <2.0.0.)
1.2.x A semantic major and minor version. (This example would match 1.2.3 but not 1.3.0,
and is shorthand for >=1.2.0 <1.3.0.)
Note: You cannot mix semantic versioning shorthand (.x) with greater/less than versioning syntax.
Warning: The full name in a dependency must use a slash between the username and
module name. This is dierent from the name format used elsewhere in metadata.json.This
is a legacy architecture problem with the Puppet Forge, and we apologize for the
inconvenience. We are working on a solution.
Puppet 3.6 Reference Manual Publishing Modules on the Puppet Forge 139/325
The following would be incorrect.
>= 3.2.x
< 4.x
Build Your Module
With Puppet 3.6s updates to the puppet module tool (PMT), the process for building your module
will be slightly dierent based on the les in your modules directory.
I generated a new module using puppet module generate
I have a Modulele and no metadata.json
I have a Modulele and a metadata.json
I have a Modulele and a partial* metadata.json
How do you know if your metadata.json is partial or complete? For your metadata.json to be
complete, it must contain all the metadata elds listed in the Write a metadata.json File section
above. If any of these elds are missing, your metadata.json is considered partial: name, version,
author, license, summary, source, dependencies.
Brand new module
If you used puppet module generate to create your module and youre using Puppet 3.6, your
metadata.json le was created for you! All you need to do is build a package of your module by
running the following command:
A Note on Semantic Versioning
When writing your metadata.json le, youre setting a version for your own module and
optionally expressing dependencies on others module versions. We strongly recommend
following the Semantic Versioning specication. Doing so allows others to rely on your
modules without unexpected change.
Many other users already use semantic versioning, and you can take advantage of this in
your modules dependencies. For example, if you depend on puppetlabs/stdlib and want to
allow updates while avoiding breaking changes, you could write the following line in your
metadata.json (assuming a current stdlib version of 4.2.1):
"dependencies": [
{ "name": "puppetlabs/stdlib", "version_requirement": "4.x" },
]
Puppet 3.6 Reference Manual Publishing Modules on the Puppet Forge 140/325
# puppet module build <MODULE DIRECTORY>
This generates a .tar.gz package, which is saved in the modules pkg/ subdirectory.
For example:
# puppet module build /etc/puppetlabs/puppet/modules/mymodule
Building /etc/puppetlabs/puppet/modules/mymodule for release
/etc/puppetlabs/puppet/modules/mymodule/pkg/examplecorp-mymodule-0.0.1.tar.gz
Modulele, no metadata.json
If you have a Modulele but no metadata.json le, you will receive a deprecation warning when you
build a package of your module. Below are the steps for building your module package and
resolving the deprecation.
First, run the build command.
# puppet module build <MODULE DIRECTORY>
You will receive the deprecation warning, but the PMT will build you a complete metadata.json le
and place it in both your build directory and root module directory. To avoid future warnings,
delete the Modulele, as it is no longer necessary.
Modulele and metadata.json
If you have a complete metadata.json, even one with extra elds, the PMT will merge your
Modulele and metadata.json les.
Run the build command.
# puppet module build <MODULE DIRECTORY>
You will receive a deprecation warning, but the PMT will merge your Moduleles information in
your metadata.json. An updated version of your metadata.json le will be placed in both your build
directory and root module directory. To avoid future warnings, delete the Modulele, as it is no
longer necessary.
Modulele and partial metadata.json
If your metadata.json is missing required elds but you have a complete Modulele, you can go
through the build process but will need to perform some additional steps to remove the
deprecation warning.
Run the build command.
Puppet 3.6 Reference Manual Publishing Modules on the Puppet Forge 141/325
# puppet module build <MODULE DIRECTORY>
You will receive a deprecation warning. The PMT will merge your Modulele and metadata.json le
into a single metadata.json. To avoid future warnings, you need to copy the metadata.json from the
/pkg directory within the build directory and place it in your modules root directory. You can then
delete the Modulele.
Upload to the Puppet Forge
Now that you have a compiled tar.gz package, you can upload it to the Puppet Forge. There is
currently no command line tool for publishing; you must use the Puppet Forges web interface.
In your web browser, navigate to the Puppet Forge and log in.
Create a Module Page
If you have never published this module before, you must create a new page for it.
Create a Release
1. Click the Publish a Module in the sidebar:
1. Fill in the module form that opens. Only the Module Name eld is required. Use the modules
short name, not the long username-module name.
2. Click the Publish Module button at the bottom of the form. Doing so automatically takes you to
the new module page.
1. Navigate to the modules page if you are not already there, and click the Click here to upload
your tarball link:
Puppet 3.6 Reference Manual Publishing Modules on the Puppet Forge 142/325
This will bring you to the upload form:
Your module has now been published to the Puppet Forge. The Forge will pull your README,
Changelog, and License les from your tarball to display on your modules page. To conrm that it
was published correctly, you can install it on a new system using the puppet module install
action.
Release a New Version
1. Click Choose File and use the le browser to locate and select the release tarball you created
with the puppet module build action. Then click the Upload Release link.
1. To release a new version of an already published module, make any necessary edits to your
module, and then increment the version eld in the metadata.json le (ensuring you use a valid
semantic version).
2. When youre ready to publish your new version, navigate to the Puppet Forge and log in if
necessary. Click the Upload a New Release link:
Puppet 3.6 Reference Manual Publishing Modules on the Puppet Forge 143/325
This will bring you to the upload form as mentioned in Create a Release above, where you can
select the new release tarball and upload the release.
Documenting Modules
Puppet 3.6 Reference Manual Documenting Modules 144/325
Documenting Modules
You are encouraged to document any module you write, whether you intend the module solely for
internal use or for publication on the Puppet Forge. Documenting your module will help future-you
remember what your module was built to do and can help explain why you chose to do things one
way versus another. And anyone else using your module will denitely appreciate it.
There is a README template to assist you in putting together complete and clear documentation.
Continue reading to learn README best practices.
See Installing Modules for how to install pre-built modules from the Puppet Forge.
See Publishing Modules for how to publish your modules to the Puppet Forge.
See Using Plugins for how to arrange plugins (like custom facts and custom resource types) in
modules and sync them to agent nodes.
README Template
Below we will walk through the template. If you would like a standalone copy of the template, you
can nd it here.
We start with listing the modules name, followed by a table of contents.
#modulename
####Table of Contents
1. [Overview](#overview)
2. [Module Description - What the module does and why it is useful](#module-
description)
3. [Setup - The basics of getting started with [Modulename]](#setup)
* [What [Modulename] affects](#what-[modulename]-affects)
* [Setup requirements](#setup-requirements)
* [Beginning with [Modulename]](#beginning-with-[Modulename])
4. [Usage - Configuration options and additional functionality](#usage)
5. [Reference - An under-the-hood peek at what the module is doing and
how](#reference)
5. [Limitations - OS compatibility, etc.](#limitations)
6. [Development - Guide for contributing to the module](#development)
The table of contents is optional but suggested as best practice, particularly for larger or more
complicated modules.
The table of contents is followed by a brief, overview summary of your module.
##Overview
A one-maybe-two sentence summary of what the module does/what problem it
Puppet 3.6 Reference Manual Documenting Modules 145/325
solves. This is your 30 second elevator pitch for your module. Consider
including OS/Puppet version it works with.
For modules used internally, the overview section may be omitted.
The overview is followed by a more-detailed description of your module.
##Module Description
If applicable, this section should have a brief description of the technology
the module integrates with and what that integration enables. This section
should answer the questions: "What does this module *do*?" and "Why would I use
it?"
If your module has a range of functionality (installation, configuration,
management, etc.) this is the time to mention it.
The module description is the section that will explain to future-you why present-you created the
module and what you were trying to do with it.
Then we get to the parts dealing with actually using the module, beginning with setting the module
up.
##Setup
###What [Modulename] affects
* A list of files, packages, services, or operations that the module will
alter, impact, or execute on the system it's installed on.
* This is a great place to stick any warnings.
* Can be in list or paragraph form.
###Setup Requirements **OPTIONAL**
If your module requires anything extra before setting up (pluginsync enabled,
etc.), mention it here.
###Beginning with [Modulename]
The very basic steps needed for a user to get the module up and running.
If your most recent release breaks compatibility or requires particular steps
for upgrading, you may wish to include an additional section here: Upgrading
(For an example, see http://forge.puppetlabs.com/puppetlabs/firewall).
The setup section is really intended as a guide to getting the module installed and running at a very
basic level so the user can get a sense of what it does and how it works in their environment.
After setting the module up, the template moves on to using the module and conguring it to a
user or environments particular needs.
Puppet 3.6 Reference Manual Documenting Modules 146/325
##Usage
Put the classes, types, and resources for customizing, configuring, and doing
the fancy stuff with your module here.
`If you only ll out one section, make it the usage section.
All of the technical details come through in the reference section.
##Reference
Here, list the classes, types, providers, facts, etc contained in your module.
This section should include all of the under-the-hood workings of your module
so people know what the module is touching on their system but don't need to
mess with things. (We are working on automating this section!)
As it notes, the reference section is in the process of being automated.
Finally, include any additional information about your module and its limitations, contribution
requirements, etc.
##Limitations
This is where you list OS compatibility, version compatibility, etc.
##Development
Since your module is awesome, other users will want to play with it. Let them
know what the ground rules for contributing are.
##Release Notes/Contributors/Etc **Optional**
If you aren't using changelog, put your release notes here (though you should
consider using changelog). You may also add any additional sections you feel
are necessary or important to include here. Please use the `## ` header.
Style guide for module documentation is coming soon!
Type Reference
Due to technical diculties, this page cannot be displayed in this PDF le. To view this page on the
web, please see http://docs.puppetlabs.com/references/3.6.latest/type.html.
Conguration Reference
Puppet 3.6 Reference Manual Type Reference 147/325
Puppet 3.6 Reference Manual Type Reference 148/325
Conguration Reference
This page is autogenerated; any changes will get overwritten (last generated on 2014-06-12
11:06:27 -0700)
Conguration Settings
Each of these settings can be specied in puppet.conf or on the command line.
When using boolean settings on the command line, use --setting and --no-setting instead of
--setting (true|false).
Settings can be interpolated as $variables in other settings; $environment is special, in that
puppet master will interpolate each agent nodes environment instead of its own.
Multiple values should be specied as comma-separated lists; multiple directories should be
separated with the system path separator (usually a colon).
Settings that represent time intervals should be specied in duration format: an integer
immediately followed by one of the units y (years of 365 days), d (days), h (hours), m
(minutes), or s (seconds). The unit cannot be combined with other units, and defaults to
seconds when omitted. Examples are 3600 which is equivalent to 1h (one hour), and 1825d
which is equivalent to 5y (5 years).
Settings that take a single le or directory can optionally set the owner, group, and mode for
their value: rundir = $vardir/run { owner = puppet, group = puppet, mode = 644 }
The Puppet executables will ignore any setting that isnt relevant to their function.
See the conguration guidefor more details.
agent_catalog_run_lockle
A lock le to indicate that a puppet agent catalog run is currently in progress. The le contains the
pid of the process that holds the lock on the catalog run.
Default: $statedir/agent_catalog_run.lock
agent_disabled_lockle
A lock le to indicate that puppet agent runs have been administratively disabled. File contains a
JSON object with state information.
Default: $statedir/agent_disabled.lock
allow_duplicate_certs
Whether to allow a new certicate request to overwrite an existing certicate.
Default: false
Puppet 3.6 Reference Manual Conguration Reference 149/325
allow_variables_with_dashes
Permit hyphens ( -) in variable names and issue deprecation warnings about them. This setting
should always be false; setting it to true will cause subtle and wide-ranging bugs. It will be
removed in a future version.
Hyphenated variables caused major problems in the language, but were allowed between Puppet
2.7.3 and 2.7.14. If you used them during this window, we apologize for the inconvenience you
can temporarily set this to true in order to upgrade, and can rename your variables at your leisure.
Please revert it to false after you have renamed all aected variables.
Default: false
archive_le_server
During an inspect run, the le bucket server to archive les to if archive_les is set.
Default: $server
archive_les
During an inspect run, whether to archive les whose contents are audited to a le bucket.
Default: false
async_storecongs
Whether to use a queueing system to provide asynchronous database integration. Requires that
puppet queue be running.
Default: false
autoush
Whether log les should always ush to disk.
Default: true
autosign
Whether (and how) to autosign certicate requests. This setting is only relevant on a puppet master
acting as a certicate authority (CA).
Valid values are true (autosigns all certicate requests; not recommended), false (disables
autosigning certicates), or the absolute path to a le.
The le specied in this setting may be either a conguration leor a custom policy executable.
Puppet will automatically determine what it is: If the Puppet user (see the user setting) can execute
the le, it will be treated as a policy executable; otherwise, it will be treated as a cong le.
If a custom policy executable is congured, the CA puppet master will run it every time it receives a
Puppet 3.6 Reference Manual Conguration Reference 150/325
CSR. The executable will be passed the subject CN of the request as a command line argument, and
the contents of the CSR in PEM format on stdin. It should exit with a status of 0 if the cert should be
autosigned and non-zero if the cert should not be autosigned.
If a certicate request is not autosigned, it will persist for review. An admin user can use the puppet
cert sign command to manually sign it, or can delete the request.
For info on autosign conguration les, see the guide to Puppets cong les.
Default: $confdir/autosign.conf
basemodulepath
The search path for global modules. Should be specied as a list of directories separated by the
system path separator character. (The POSIX path separator is :, and the Windows path separator
is ;.)
If you are using directory environments, these are the modules that will be used by all
environments. Note that the modules directory of the active environment will have priority over any
global directories. For more info, see
http://docs.puppetlabs.com/puppet/latest/reference/environments.html
This setting also provides the default value for the deprecated modulepath setting, which is used
when directory environments are disabled.
Default: $confdir/modules:/usr/share/puppet/modules
bi
Turns on Bi the catalog builder, future parser, and future evaluator. This is an experimental
feature - and this setting may go away before release of Pupet 3.6.
Default: false
bindaddress
The address a listening server should bind to.
Default: 0.0.0.0
binder
Turns the binding system on or o. This includes bindings in modules. The binding system
aggregates data from modules and other locations and makes them available for lookup. The
binding system is experimental and any or all of it may change.
Default: false
binder_cong
The binder conguration le. Puppet reads this le on each request to congure the bindings
Puppet 3.6 Reference Manual Conguration Reference 151/325
system. If set to nil (the default), a $confdir/binder_cong.yaml is optionally loaded. If it does not
exists, a default conguration is used. If the setting :binding_cong is specied, it must reference a
valid and existing yaml le.
Default:
bucketdir
Where FileBucket les are stored.
Default: $vardir/bucket
ca
Whether the master should function as a certicate authority.
Default: true
ca_name
The name to use the Certicate Authority certicate.
Default: Puppet CA: $certname
ca_port
The port to use for the certicate authority.
Default: $masterport
ca_server
The server to use for certicate authority requests. Its a separate server because it cannot and does
not need to horizontally scale.
Default: $server
ca_ttl
The default TTL for new certicates. This setting can be a time interval in seconds (30 or 30s),
minutes (30m), hours (6h), days (2d), or years (5y).
Default: 5y
cacert
The CA certicate.
Default: $cadir/ca_crt.pem
cacrl
The certicate revocation list (CRL) for the CA. Will be used if present but otherwise ignored.
Default: $cadir/ca_crl.pem
Puppet 3.6 Reference Manual Conguration Reference 152/325
cadir
The root directory for the certicate authority.
Default: $ssldir/ca
cakey
The CA private key.
Default: $cadir/ca_key.pem
capass
Where the CA stores the password for the private key.
Default: $caprivatedir/ca.pass
caprivatedir
Where the CA stores private certicate information.
Default: $cadir/private
capub
The CA public key.
Default: $cadir/ca_pub.pem
catalog_cache_terminus
How to store cached catalogs. Valid values are json, msgpack and yaml. The agent application
defaults to json.
Default:
catalog_format
(Deprecated for preferred_serialization_format) What format to use to dump the catalog. Only
supports marshal and yaml. Only matters on the client, since it asks the server for a specic
format.
catalog_terminus
Where to get node catalogs. This is useful to change if, for instance, youd like to pre-compile
catalogs and store them in memcached or some other easily-accessed store.
Default: compiler
cert_inventory
The inventory le. This is a text le to which the CA writes a complete listing of all certicates.
Puppet 3.6 Reference Manual Conguration Reference 153/325
Default: $cadir/inventory.txt
certdir
The certicate directory.
Default: $ssldir/certs
certdnsnames
The certdnsnames setting is no longer functional, after CVE-2011-3872. We ignore the value
completely.
For your own certicate request you can set dns_alt_names in the conguration and it will apply
locally. There is no conguration option to set DNS alt names, or any other subjectAltName value,
for another nodes certicate.
Alternately you can use the --dns_alt_names command line option to set the labels added while
generating your own CSR.
certicate_expire_warning
The window of time leading up to a certicates expiration that a notication will be logged. This
applies to CA, master, and agent certicates. This setting can be a time interval in seconds (30 or
30s), minutes (30m), hours (6h), days (2d), or years (5y).
Default: 60d
certicate_revocation
Whether certicate revocation should be supported by downloading a Certicate Revocation List
(CRL) to all clients. If enabled, CA chaining will almost denitely not work.
Default: true
certname
The name to use when handling certicates. Defaults to the fully qualied domain name.
Default: (the systems fully qualied domain name)
classle
The le in which puppet agent stores a list of the classes associated with the retrieved
conguration. Can be loaded in the separate puppet executable using the --loadclasses option.
Default: $statedir/classes.txt
client_datadir
The directory in which serialized data is stored on the client.
Puppet 3.6 Reference Manual Conguration Reference 154/325
Default: $vardir/client_data
clientbucketdir
Where FileBucket les are stored locally.
Default: $vardir/clientbucket
clientyamldir
The directory in which client-side YAML data is stored.
Default: $vardir/client_yaml
code
Code to parse directly. This is essentially only used by puppet, and should only be set if youre
writing your own Puppet executable.
color
Whether to use colors when logging to the console. Valid values are ansi (equivalent to true),
html, and false, which produces no color. Defaults to false on Windows, as its console does not
support ansi colors.
Default: ansi
confdir
The main Puppet conguration directory. The default for this setting is calculated based on the
user. If the process is running as root or the user that Puppet is supposed to run as, it defaults to a
system directory, but if its running as any other user, it defaults to being in the users home
directory.
Default: /etc/puppet
cong
The conguration le for the current puppet application.
Default: $confdir/${cong_le_name}
cong_le_name
The name of the puppet cong le.
Default: puppet.conf
cong_version
How to determine the conguration version. By default, it will be the time that the conguration is
parsed, but you can provide a shell script to override how the version is determined. The output of
this script will be added to every log message in the reports, allowing you to correlate changes on
Puppet 3.6 Reference Manual Conguration Reference 155/325
your hosts to the source version on the server.
Setting a global value for cong_version in puppet.conf is deprecated. Please set a per-
environment value in environment.conf instead. For more info, see
http://docs.puppetlabs.com/puppet/latest/reference/environments.html
congprint
Print the value of a specic conguration setting. If the name of a setting is provided for this, then
the value is printed and puppet exits. Comma-separate multiple values. For a list of all values,
specify all.
congtimeout
How long the client should wait for the conguration to be retrieved before considering it a failure.
This can help reduce apping if too many clients contact the server at one time. This setting can be
a time interval in seconds (30 or 30s), minutes (30m), hours (6h), days (2d), or years (5y).
Default: 2m
couchdb_url
The url where the puppet couchdb database will be created. Only used when facts_terminus is set
to couch.
Default: http://127.0.0.1:5984/puppet
csr_attributes
An optional le containing custom attributes to add to certicate signing requests (CSRs). You
should ensure that this le does not exist on your CA puppet master; if it does, unwanted certicate
extensions may leak into certicates created with the puppet cert generate command.
If present, this le must be a YAML hash containing a custom_attributes key and/or an
extension_requests key. The value of each key must be a hash, where each key is a valid OID and
each value is an object that can be cast to a string.
Custom attributes can be used by the CA when deciding whether to sign the certicate, but are then
discarded. Attribute OIDs can be any OID value except the standard CSR attributes (i.e. attributes
described in RFC 2985 section 5.4). This is useful for embedding a pre-shared key for autosigning
policy executables (see the autosign setting), often by using the 1.2.840.113549.1.9.7
(challenge password) OID.
Extension requests will be permanently embedded in the nal certicate. Extension OIDs must be in
the ppRegCertExt ( 1.3.6.1.4.1.34380.1.1) or ppPrivCertExt ( 1.3.6.1.4.1.34380.1.2) OID
arcs. The ppRegCertExt arc is reserved for four of the most common pieces of data to embed:
pp_uuid ( .1), pp_instance_id ( .2), pp_image_name ( .3), and pp_preshared_key ( .4) in the
YAML le, these can be referred to by their short descriptive names instead of their full OID. The
Puppet 3.6 Reference Manual Conguration Reference 156/325
ppPrivCertExt arc is unregulated, and can be used for site-specic extensions.
Default: $confdir/csr_attributes.yaml
csrdir
Where the CA stores certicate requests
Default: $cadir/requests
daemonize
Whether to send the process into the background. This defaults to true on POSIX systems, and to
false on Windows (where Puppet currently cannot daemonize).
Default: true
data_binding_terminus
Where to retrive information about data.
Default: hiera
dbadapter
The type of database to use. This setting is only used by the ActiveRecord storecongs and
inventory backends, which are deprecated.
Default: sqlite3
dbconnections
The number of database connections for networked databases. Will be ignored unless the value is a
positive integer. This setting is only used by the ActiveRecord storecongs and inventory backends,
which are deprecated.
dblocation
The sqlite database le. This setting is only used by the ActiveRecord storecongs and inventory
backends, which are deprecated.
Default: $statedir/clientcongs.sqlite3
dbmigrate
Whether to automatically migrate the database. This setting is only used by the ActiveRecord
storecongs and inventory backends, which are deprecated.
Default: false
dbname
The name of the database to use. This setting is only used by the ActiveRecord storecongs and
Puppet 3.6 Reference Manual Conguration Reference 157/325
inventory backends, which are deprecated.
Default: puppet
dbpassword
The database password for caching. Only used when networked databases are used. This setting is
only used by the ActiveRecord storecongs and inventory backends, which are deprecated.
Default: puppet
dbport
The database password for caching. Only used when networked databases are used. This setting is
only used by the ActiveRecord storecongs and inventory backends, which are deprecated.
dbserver
The database server for caching. Only used when networked databases are used.
Default: localhost
dbsocket
The database socket location. Only used when networked databases are used. Will be ignored if the
value is an empty string. This setting is only used by the ActiveRecord storecongs and inventory
backends, which are deprecated.
dbuser
The database user for caching. Only used when networked databases are used. This setting is only
used by the ActiveRecord storecongs and inventory backends, which are deprecated.
Default: puppet
default_le_terminus
The default source for les if no server is given in a uri, e.g. puppet:///le. The default of rest
causes the le to be retrieved using the server setting. When running apply the default is
file_server, causing requests to be lled locally.
Default: rest
default_schedules
Boolean; whether to generate the default schedule resources. Setting this to false is useful for
keeping external report processors clean of skipped schedule resources.
Default: true
devicecong
Path to the device cong le for puppet device.
Puppet 3.6 Reference Manual Conguration Reference 158/325
Default: $confdir/device.conf
devicedir
The root directory of devices $vardir.
Default: $vardir/devices
di
Which di command to use when printing dierences between les. This setting has no default
value on Windows, as standard diff is not available, but Puppet can use many third-party di
tools.
Default: di
di_args
Which arguments to pass to the di command when printing dierences between les. The
command to use can be chosen with the diff setting.
Default: -u
digest_algorithm
Which digest algorithm to use for le resources and the lebucket. Valid values are md5, sha256.
Default is md5.
Default: md5
disable_warnings
A list of warning types to disable. Currently the only warning type that can be disabled are
deprecations, but more warning types may be added later.
Default: []
dns_alt_names
The comma-separated list of alternative DNS names to use for the local host.
When the node generates a CSR for itself, these are added to the request as the desired
subjectAltName in the certicate: additional DNS labels that the certicate is also valid answering
as.
This is generally required if you use a non-hostname certname, or if you want to use puppet kick
or puppet resource -H and the primary certname does not match the DNS name you use to
communicate with the host.
This is unnecessary for agents, unless you intend to use them as a server for puppet kick or
Puppet 3.6 Reference Manual Conguration Reference 159/325
remote puppet resource management.
It is rarely necessary for servers; it is usually helpful only if you need to have a pool of multiple load
balanced masters, or for the same master to respond on two physically separate networks under
dierent names.
document_all
Whether to document all resources when using puppet doc to generate manifest documentation.
Default: false
dynamicfacts
(Deprecated) Facts that are dynamic; these facts will be ignored when deciding whether changed
facts should result in a recompile. Multiple facts should be comma-separated.
Default: memorysize,memoryfree,swapsize,swapfree
environment
The environment Puppet is running in. For clients (e.g., puppet agent) this determines the
environment itself, which is used to nd modules and much more. For servers (i.e., puppet master)
this provides the default environment for nodes we know nothing about.
Default: production
environment_timeout
The time to live for a cached environment. The time is either given This setting can be a time
interval in seconds (30 or 30s), minutes (30m), hours (6h), days (2d), or years (5y)., or the word
unlimited which causes the environment to be cached until the master is restarted.
Default: 3m
environmentpath
A search path for directory environments, as a list of directories separated by the system path
separator character. (The POSIX path separator is :, and the Windows path separator is ;.)
This setting must have a value set to enable directory environments. The recommended value is
$confdir/environments. For more details, see
http://docs.puppetlabs.com/puppet/latest/reference/environments.html
evaltrace
Whether each resource should log when it is being evaluated. This allows you to interactively see
exactly what is being done.
Default: false
Puppet 3.6 Reference Manual Conguration Reference 160/325
evaluator
Which evaluator to use when compiling Puppet manifests. Valid values are current and future (the
default).
Note: This setting is only used when parser = future. It allows testers to turn o the future
evaluator when doing detailed tests and comparisons of the new compilation system.
Evaluation is the second stage of catalog compilation. After the parser converts a manifest to a
model of expressions, the evaluator processes each expression. (For example, a resource
declaration signals the evaluator to add a resource to the catalog).
The future parser and evaluator are slated to become default in Puppet 4. Their purpose is to add
new features and improve consistency and reliability.
Available Since Puppet 3.5.
Default: future
external_nodes
An external command that can produce node information. The commands output must be a YAML
dump of a hash, and that hash must have a classes key and/or a parameters key, where classes
is an array or hash and parameters is a hash. For unknown nodes, the command should exit with a
non-zero exit code.
This command makes it straightforward to store your node mapping information in other data
sources like databases.
Default: none
factpath
Where Puppet should look for facts. Multiple directories should be separated by the system path
separator character. (The POSIX path separator is :, and the Windows path separator is ;.)
Default: $vardir/lib/facter:$vardir/facts
facts_terminus
The node facts terminus.
Default: facter
leservercong
Where the leserver conguration is stored.
Default: $confdir/leserver.conf
letimeout
Puppet 3.6 Reference Manual Conguration Reference 161/325
The minimum time to wait between checking for updates in conguration les. This timeout
determines how quickly Puppet checks whether a le (such as manifests or templates) has changed
on disk. This setting can be a time interval in seconds (30 or 30s), minutes (30m), hours (6h), days
(2d), or years (5y).
Default: 15s
freeze_main
Freezes the main class, disallowing any code to be added to it. This essentially means that you
cant have any code outside of a node, class, or denition other than in the site manifest.
Default: false
gencong
When true, causes Puppet applications to print an example cong le to stdout and exit. The
example will include descriptions of each setting, and the current (or default) value of each setting,
incorporating any settings overridden on the CLI (with the exception of genconfig itself). This
setting only makes sense when specied on the command line as --genconfig.
Default: false
genmanifest
Whether to just print a manifest to stdout and exit. Only makes sense when specied on the
command line as --genmanifest. Takes into account arguments specied on the CLI.
Default: false
graph
Whether to create dot graph les for the dierent conguration graphs. These dot les can be
interpreted by tools like OmniGrae or dot (which is part of ImageMagick).
Default: false
graphdir
Where to store dot-outputted graphs.
Default: $statedir/graphs
group
The group puppet master should run as.
Default: puppet
hiera_cong
The hiera conguration le. Puppet only reads this le on startup, so you must restart the puppet
Puppet 3.6 Reference Manual Conguration Reference 162/325
master every time you edit it.
Default: $confdir/hiera.yaml
hostcert
Where individual hosts store and look for their certicates.
Default: $certdir/$certname.pem
hostcrl
Where the hosts certicate revocation list can be found. This is distinct from the certicate
authoritys CRL.
Default: $ssldir/crl.pem
hostcsr
Where individual hosts store and look for their certicate requests.
Default: $ssldir/csr_$certname.pem
hostprivkey
Where individual hosts store and look for their private key.
Default: $privatekeydir/$certname.pem
hostpubkey
Where individual hosts store and look for their public key.
Default: $publickeydir/$certname.pem
http_compression
Allow http compression in REST communication with the master. This setting might improve
performance for agent -> master communications over slow WANs. Your puppet master needs to
support compression (usually by activating some settings in a reverse-proxy in front of the puppet
master, which rules out webrick). It is harmless to activate this settings if your master doesnt
support compression, but if it supports it, this setting might reduce performance on high-speed
LANs.
Default: false
http_proxy_host
The HTTP proxy host to use for outgoing connections. Note: You may need to use a FQDN for the
server hostname when using a proxy.
Default: none
http_proxy_port
Puppet 3.6 Reference Manual Conguration Reference 163/325
http_proxy_port
The HTTP proxy port to use for outgoing connections
Default: 3128
httplog
Where the puppet agent web server logs.
Default: $logdir/http.log
ignorecache
Ignore cache and always recompile the conguration. This is useful for testing new congurations,
where the local cache may in fact be stale even if the timestamps are up to date - if the facts change
or if the server changes.
Default: false
ignoreimport
If true, allows the parser to continue without requiring all les referenced with import statements
to exist. This setting was primarily designed for use with commit hooks for parse-checking.
Default: false
ignoremissingtypes
Skip searching for classes and denitions that were missing during a prior compilation. The list of
missing objects is maintained per-environment and persists until the environment is cleared or the
master is restarted.
Default: false
ignoreschedules
Boolean; whether puppet agent should ignore schedules. This is useful for initial puppet agent
runs.
Default: false
immutable_node_data
When true, also prevents $trusted and $facts from being overridden in any scope
Default: $trusted_node_data
inventory_port
The port to communicate with the inventory_server.
Default: $masterport
inventory_server
Puppet 3.6 Reference Manual Conguration Reference 164/325
The server to send facts to.
Default: $server
inventory_terminus
Should usually be the same as the facts terminus
Default: $facts_terminus
keylength
The bit length of keys.
Default: 4096
lastrunle
Where puppet agent stores the last run report summary in yaml format.
Default: $statedir/last_run_summary.yaml
lastrunreport
Where puppet agent stores the last run report in yaml format.
Default: $statedir/last_run_report.yaml
ldapattrs
The LDAP attributes to include when querying LDAP for nodes. All returned attributes are set as
variables in the top-level scope. Multiple values should be comma-separated. The value all returns
all attributes.
Default: all
ldapbase
The search base for LDAP searches. Its impossible to provide a meaningful default here, although
the LDAP libraries might have one already set. Generally, it should be the ou=Hosts branch under
your main directory.
ldapclassattrs
The LDAP attributes to use to dene Puppet classes. Values should be comma-separated.
Default: puppetclass
ldapparentattr
The attribute to use to dene the parent node.
Default: parentnode
Puppet 3.6 Reference Manual Conguration Reference 165/325
ldappassword
The password to use to connect to LDAP.
ldapport
The LDAP port. Only used if node_terminus is set to ldap.
Default: 389
ldapserver
The LDAP server. Only used if node_terminus is set to ldap.
Default: ldap
ldapssl
Whether SSL should be used when searching for nodes. Defaults to false because SSL usually
requires certicates to be set up on the client side.
Default: false
ldapstackedattrs
The LDAP attributes that should be stacked to arrays by adding the values in all hierarchy elements
of the tree. Values should be comma-separated.
Default: puppetvar
ldapstring
The search string used to nd an LDAP node.
Default: (&(objectclass=puppetClient)(cn=%s))
ldaptls
Whether TLS should be used when searching for nodes. Defaults to false because TLS usually
requires certicates to be set up on the client side.
Default: false
ldapuser
The user to use to connect to LDAP. Must be specied as a full DN.
legacy_query_parameter_serialization
The serialization format to use when sending le_metadata query parameters. Older versions of
puppet master expect certain query parameters to be serialized as yaml, which is deprecated.
This should almost always be false. It can be temporarily set to true to let agents using this Puppet
version connect to a puppet master running Puppet 3.0.0 through 3.2.x.
Puppet 3.6 Reference Manual Conguration Reference 166/325
Note that this is set to true automatically if the agent detects an older master, so should never need
to be set explicitly.
Default: false
libdir
An extra search path for Puppet. This is only useful for those les that Puppet will load on demand,
and is only guaranteed to work for those cases. In fact, the autoload mechanism is responsible for
making sure this directory is in Rubys search path
Default: $vardir/lib
listen
Whether puppet agent should listen for connections. If this is true, then puppet agent will accept
incoming REST API requests, subject to the default ACLs and the ACLs set in the rest_authconfig
le. Puppet agent can respond usefully to requests on the run, facts, certificate, and resource
endpoints.
Default: false
localcacert
Where each client stores the CA certicate.
Default: $certdir/ca.pem
localcong
Where puppet agent caches the local conguration. An extension indicating the cache format is
added automatically.
Default: $statedir/localcong
log_level
Default logging level
Default: notice
logdir
The directory in which to store log les
Default:
manage_internal_le_permissions
Whether Puppet should manage the owner, group, and mode of les it uses internally
Default: true
Puppet 3.6 Reference Manual Conguration Reference 167/325
manifest
The entry-point manifest for puppet master. This can be one le or a directory of manifests to be
evaluated in alphabetical order. Puppet manages this path as a directory if one exists or if the path
ends with a / or .
Setting a global value for manifest in puppet.conf is deprecated. Please use directory environments
instead. If you need to use something other than the environments manifests directory as the
main manifest, you can set manifest in environment.conf. For more info, see
http://docs.puppetlabs.com/puppet/latest/reference/environments.html
Default: $manifestdir/site.pp
manifestdir
Used to build the default value of the manifest setting. Has no other purpose.
This setting is deprecated.
Default: $confdir/manifests
masterhttplog
Where the puppet master web server logs.
Default: $logdir/masterhttp.log
masterlog
Where puppet master logs. This is generally not used, since syslog is the default log destination.
Default: $logdir/puppetmaster.log
masterport
The port for puppet master trac. For puppet master, this is the port to listen on; for puppet agent,
this is the port to make requests on. Both applications use this setting to get the port.
Default: 8140
max_deprecations
Sets the max number of logged/displayed parser validation deprecation warnings in case multiple
errors have been detected. A value of 0 is the same as value 1. The count is per manifest.
Default: 10
max_errors
Sets the max number of logged/displayed parser validation errors in case multiple errors have
been detected. A value of 0 is the same as value 1. The count is per manifest.
Default: 10
Puppet 3.6 Reference Manual Conguration Reference 168/325
max_warnings
Sets the max number of logged/displayed parser validation warnings in case multiple errors have
been detected. A value of 0 is the same as value 1. The count is per manifest.
Default: 10
maximum_uid
The maximum allowed UID. Some platforms use negative UIDs but then ship with tools that do not
know how to handle signed ints, so the UIDs show up as huge numbers that can then not be fed
back into the system. This is a hackish way to fail in a slightly more useful way when that happens.
Default: 4294967290
mkusers
Whether to create the necessary user and group that puppet agent will run as.
Default: false
module_repository
The module repository
Default: https://forgeapi.puppetlabs.com
module_skeleton_dir
The directory which the skeleton for module tool generate is stored.
Default: $module_working_dir/skeleton
module_working_dir
The directory into which module tool data is stored
Default: $vardir/puppet-module
modulepath
The search path for modules, as a list of directories separated by the system path separator
character. (The POSIX path separator is :, and the Windows path separator is ;.)
Setting a global value for modulepath in puppet.conf is deprecated. Please use directory
environments instead. If you need to use something other than the default modulepath of <ACTIVE
ENVIRONMENT'S MODULES DIR>:$basemodulepath, you can set modulepath in environment.conf. For
more info, see http://docs.puppetlabs.com/puppet/latest/reference/environments.html
Default: $basemodulepath
name
Puppet 3.6 Reference Manual Conguration Reference 169/325
The name of the application, if we are running as one. The default is essentially $0 without the path
or .rb.
Default:
node_cache_terminus
How to store cached nodes. Valid values are (none), json, msgpack, yaml or write only yaml
(write_only_yaml). The master application defaults to write_only_yaml, all others to none.
Default:
node_name
How the puppet master determines the clients identity and sets the hostname, fqdn and domain
facts for use in the manifest, in particular for determining which node statement applies to the
client. Possible values are cert (use the subjects CN in the clients certicate) and facter (use the
hostname that the client reported in its facts)
Default: cert
node_name_fact
The fact name used to determine the node name used for all requests the agent makes to the
master. WARNING: This setting is mutually exclusive with node_name_value. Changing this setting
also requires changes to the default auth.conf conguration on the Puppet Master. Please see
http://links.puppetlabs.com/node_name_fact for more information.
node_name_value
The explicit value used for the node name for all requests the agent makes to the master.
WARNING: This setting is mutually exclusive with node_name_fact. Changing this setting also
requires changes to the default auth.conf conguration on the Puppet Master. Please see
http://links.puppetlabs.com/node_name_value for more information.
Default: $certname
node_terminus
Where to nd information about nodes.
Default: plain
noop
Whether to apply catalogs in noop mode, which allows Puppet to partially simulate a normal run.
This setting aects puppet agent and puppet apply.
When running in noop mode, Puppet will check whether each resource is in sync, like it does when
running normally. However, if a resource attribute is not in the desired state (as declared in the
catalog), Puppet will take no action, and will instead report the changes it would have made. These
Puppet 3.6 Reference Manual Conguration Reference 170/325
simulated changes will appear in the report sent to the puppet master, or be shown on the console
if running puppet agent or puppet apply in the foreground. The simulated changes will not send
refresh events to any subscribing or notied resources, although Puppet will log that a refresh
event would have been sent.
Important note: The noop metaparameter allows you to apply individual resources in noop mode,
and will override the global value of the noop setting. This means a resource with noop => false
will be changed if necessary, even when running puppet agent with noop = true or --noop.
(Conversely, a resource with noop => true will only be simulated, even when noop mode is
globally disabled.)
Default: false
onetime
Perform one conguration run and exit, rather than spawning a long-running daemon. This is
useful for interactively running puppet agent, or running puppet agent from cron.
Default: false
ordering
How unrelated resources should be ordered when applying a catalog. Allowed values are title-
hash, manifest, and random. This setting aects puppet agent and puppet apply, but not puppet
master.
title-hash (the default) will order resources randomly, but will use the same order across runs
and across nodes.
manifest will use the order in which the resources were declared in their manifest les.
random will order resources randomly and change their order with each run. This can work like a
fuzzer for shaking out undeclared dependencies.
Regardless of this settings value, Puppet will always obey explicit dependencies set with the
before/require/notify/subscribe metaparameters and the ->/~> chaining arrows; this setting only
aects the relative ordering of unrelated resources.
Default: title-hash
parser
Selects the parser to use for parsing puppet manifests (in puppet DSL language/.pp les).
Available choices are current (the default) and future.
The curent parser means that the released version of the parser should be used.
The future parser is a time travel to the future allowing early exposure to new language features.
What these features are will vary from release to release and they may be invididually congurable.
Puppet 3.6 Reference Manual Conguration Reference 171/325
Available Since Puppet 3.2.
Default: current
passle
Where puppet agent stores the password for its private key. Generally unused.
Default: $privatedir/password
path
The shell search path. Defaults to whatever is inherited from the parent process.
Default: none
pidle
The le containing the PID of a running process. This le is intended to be used by service
management frameworks and monitoring systems to determine if a puppet process is still in the
process table.
Default: $rundir/${run_mode}.pid
plugindest
Where Puppet should store plugins that it pulls down from the central server.
Default: $libdir
pluginfactdest
Where Puppet should store external facts that are being handled by pluginsync
Default: $vardir/facts.d
pluginfactsource
Where to retrieve external facts for pluginsync
Default: puppet://$server/pluginfacts
pluginsignore
What les to ignore when pulling down plugins.
Default: .svn CVS .git
pluginsource
From where to retrieve plugins. The standard Puppet file type is used for retrieval, so anything
that is a valid le source can be used here.
Default: puppet://$server/plugins
Puppet 3.6 Reference Manual Conguration Reference 172/325
pluginsync
Whether plugins should be synced with the central server.
Default: true
postrun_command
A command to run after every agent run. If this command returns a non-zero return code, the
entire Puppet run will be considered to have failed, even though it might have performed work
during the normal run.
preferred_serialization_format
The preferred means of serializing ruby instances for passing over the wire. This wont guarantee
that all instances will be serialized using this method, since not all classes can be guaranteed to
support this format, but it will be used for all classes that support it.
Default: pson
prerun_command
A command to run before every agent run. If this command returns a non-zero return code, the
entire Puppet run will fail.
priority
The scheduling priority of the process. Valid values are high, normal, low, or idle, which are
mapped to platform-specic values. The priority can also be specied as an integer value and will
be passed as is, e.g. -5. Puppet must be running as a privileged user in order to increase
scheduling priority.
Default:
privatedir
Where the client stores private certicate information.
Default: $ssldir/private
privatekeydir
The private key directory.
Default: $ssldir/private_keys
prole
Whether to enable experimental performance proling
Default: false
Puppet 3.6 Reference Manual Conguration Reference 173/325
publickeydir
The public key directory.
Default: $ssldir/public_keys
puppetdlog
The log le for puppet agent. This is generally not used.
Default: $logdir/puppetd.log
puppetport
Which port puppet agent listens on.
Default: 8139
queue_source
Which type of queue to use for asynchronous processing. If your stomp server requires
authentication, you can include it in the URI as long as your stomp client library is at least 1.1.1
Default: stomp://localhost:61613/
queue_type
Which type of queue to use for asynchronous processing.
Default: stomp
rails_loglevel
The log level for Rails connections. The value must be a valid log level within Rails. Production
environments normally use info and other environments normally use debug. This setting is only
used by the ActiveRecord storecongs and inventory backends, which are deprecated.
Default: info
railslog
Where Rails-specic logs are sent. This setting is only used by the ActiveRecord storecongs and
inventory backends, which are deprecated.
Default: $logdir/rails.log
report
Whether to send reports after every transaction.
Default: true
report_port
The port to communicate with the report_server.
Puppet 3.6 Reference Manual Conguration Reference 174/325
Default: $masterport
report_serialization_format
The serialization format to use when sending reports to the report_server. Possible values are
pson and yaml. This setting aects puppet agent, but not puppet apply (which processes its own
reports).
This should almost always be set to pson. It can be temporarily set to yaml to let agents using this
Puppet version connect to a puppet master running Puppet 3.0.0 through 3.2.x.
Note that this is set to yaml automatically if the agent detects an older master, so should never
need to be set explicitly.
Default: pson
report_server
The server to send transaction reports to.
Default: $server
reportdir
The directory in which to store reports. Each node gets a separate subdirectory in this directory.
This setting is only used when the store report processor is enabled (see the reports setting).
Default: $vardir/reports
reportfrom
The from email address for the reports.
Default: report@(the systems fully qualied domain name)
reports
The list of report handlers to use. When using multiple report handlers, their names should be
comma-separated, with whitespace allowed. (For example, reports = http, tagmail.)
This setting is relevant to puppet master and puppet apply. The puppet master will call these report
handlers with the reports it receives from agent nodes, and puppet apply will call them with its own
report. (In all cases, the node applying the catalog must have report = true.)
See the report reference for information on the built-in report handlers; custom report handlers
can also be loaded from modules. (Report handlers are loaded from the lib directory, at
puppet/reports/NAME.rb.)
Default: store
Puppet 3.6 Reference Manual Conguration Reference 175/325
reporturl
The URL that reports should be forwarded to. This setting is only used when the http report
processor is enabled (see the reports setting).
Default: http://localhost:3000/reports/upload
req_bits
The bit length of the certicates.
Default: 4096
requestdir
Where host certicate requests are stored.
Default: $ssldir/certicate_requests
resourcele
The le in which puppet agent stores a list of the resources associated with the retrieved
conguration.
Default: $statedir/resources.txt
rest_authcong
The conguration le that denes the rights to the dierent rest indirections. This can be used as a
ne-grained authorization system for puppet master.
Default: $confdir/auth.conf
route_le
The YAML le containing indirector route conguration.
Default: $confdir/routes.yaml
rrddir
The directory where RRD database les are stored. Directories for each reporting host will be
created under this directory.
Default: $vardir/rrd
rrdinterval
How often RRD should expect data. This should match how often the hosts report back to the
server. This setting can be a time interval in seconds (30 or 30s), minutes (30m), hours (6h), days
(2d), or years (5y).
Default: $runinterval
Puppet 3.6 Reference Manual Conguration Reference 176/325
rundir
Where Puppet PID les are kept.
Default:
runinterval
How often puppet agent applies the catalog. Note that a runinterval of 0 means run continuously
rather than never run. If you want puppet agent to never run, you should start it with the --no-
client option. This setting can be a time interval in seconds (30 or 30s), minutes (30m), hours
(6h), days (2d), or years (5y).
Default: 30m
sendmail
Where to nd the sendmail binary with which to send email.
Default: /usr/sbin/sendmail
serial
Where the serial number for certicates is stored.
Default: $cadir/serial
server
The puppet master server to which the puppet agent should connect.
Default: puppet
server_datadir
The directory in which serialized data is stored, usually in a subdirectory.
Default: $vardir/server_data
show_di
Whether to log and report a contextual di when les are being replaced. This causes partial le
contents to pass through Puppets normal logging and reporting system, so this setting should be
used with caution if you are sending Puppets reports to an insecure destination. This feature
currently requires the diff/lcs Ruby library.
Default: false
signeddir
Where the CA stores signed certicates.
Default: $cadir/signed
Puppet 3.6 Reference Manual Conguration Reference 177/325
smtphelo
The name by which we identify ourselves in SMTP HELO for reports. If you send to a smtpserver
which does strict HELO checking (as with Postxs smtpd_helo_restrictions access controls), you
may need to ensure this resolves.
Default: (the systems fully qualied domain name)
smtpport
The TCP port through which to send email reports.
Default: 25
smtpserver
The server through which to send email reports.
Default: none
splay
Whether to sleep for a pseudo-random (but consistent) amount of time before a run.
Default: false
splaylimit
The maximum time to delay before runs. Defaults to being the same as the run interval. This setting
can be a time interval in seconds (30 or 30s), minutes (30m), hours (6h), days (2d), or years (5y).
Default: $runinterval
srv_domain
The domain which will be queried to nd the SRV records of servers to use.
Default: (the systems own domain)
ssl_client_ca_auth
Certicate authorities who issue server certicates. SSL servers will not be considered authentic
unless they possess a certicate issued by an authority listed in this le. If this setting has no value
then the Puppet masters CA certicate (localcacert) will be used.
Default:
ssl_client_header
The header containing an authenticated clients SSL DN. This header must be set by the proxy to the
authenticated clients SSL DN (e.g., /CN=puppet.puppetlabs.com). Puppet will parse out the
Common Name (CN) from the Distinguished Name (DN) and use the value of the CN eld for
authorization.
Puppet 3.6 Reference Manual Conguration Reference 178/325
Note that the name of the HTTP header gets munged by the web server common gateway inteface:
an HTTP_ prex is added, dashes are converted to underscores, and all letters are uppercased.
Thus, to use the X-Client-DN header, this setting should be HTTP_X_CLIENT_DN.
Default: HTTP_X_CLIENT_DN
ssl_client_verify_header
The header containing the status message of the client verication. This header must be set by the
proxy to SUCCESS if the client successfully authenticated, and anything else otherwise.
Note that the name of the HTTP header gets munged by the web server common gateway inteface:
an HTTP_ prex is added, dashes are converted to underscores, and all letters are uppercased.
Thus, to use the X-Client-Verify header, this setting should be HTTP_X_CLIENT_VERIFY.
Default: HTTP_X_CLIENT_VERIFY
ssl_server_ca_auth
Certicate authorities who issue client certicates. SSL clients will not be considered authentic
unless they possess a certicate issued by an authority listed in this le. If this setting has no value
then the Puppet masters CA certicate (localcacert) will be used.
Default:
ssldir
Where SSL certicates are kept.
Default: $confdir/ssl
statedir
The directory where Puppet state is stored. Generally, this directory can be removed without
causing harm (although it might result in spurious service restarts).
Default: $vardir/state
statele
Where puppet agent and puppet master store state associated with the running conguration. In
the case of puppet master, this le reects the state discovered through interacting with clients.
Default: $statedir/state.yaml
storecongs
Whether to store each clients conguration, including catalogs, facts, and related data. This also
enables the import and export of resources in the Puppet language - a mechanism for exchange
resources between nodes.
Puppet 3.6 Reference Manual Conguration Reference 179/325
By default this uses ActiveRecord and an SQL database to store and query the data; this, in turn, will
depend on Rails being available.
You can adjust the backend using the storecongs_backend setting.
Default: false
storecongs_backend
Congure the backend terminus used for StoreCongs. By default, this uses the ActiveRecord store,
which directly talks to the database from within the Puppet Master process.
Default: active_record
strict_hostname_checking
Whether to only search for the complete hostname as it is in the certicate when searching for node
information in the catalogs.
Default: false
strict_variables
Makes the parser raise errors when referencing unknown variables. (This does not aect
referencing variables that are explicitly set to undef).
Default: false
stringify_facts
Flatten fact values to strings using #to_s. Means you cant have arrays or hashes as fact values.
Default: true
summarize
Whether to print a transaction summary.
Default: false
syslogfacility
What syslog facility to use when logging to syslog. Syslog has a xed list of valid facilities, and you
must choose one of those; you cannot just make one up.
Default: daemon
tagmap
The mapping between reporting tags and email addresses.
Default: $confdir/tagmail.conf
tags
Puppet 3.6 Reference Manual Conguration Reference 180/325
Tags to use to nd resources. If this is set, then only resources tagged with the specied tags will
be applied. Values must be comma-separated.
templatedir
Where Puppet looks for template les. Can be a list of colon-separated directories.
This setting is deprecated. Please put your templates in modules instead.
Default: $vardir/templates
thin_storecongs
Boolean; whether Puppet should store only facts and exported resources in the storecongs
database. This will improve the performance of exported resources with the older active_record
backend, but will disable external tools that search the storecongs database. Thinning catalogs is
generally unnecessary when using PuppetDB to store catalogs.
Default: false
trace
Whether to print stack traces on some errors
Default: false
trusted_node_data
Stores trusted node data in a hash called $trusted. When true also prevents $trusted from being
overridden in any scope.
Default: false
use_cached_catalog
Whether to only use the cached catalog rather than compiling a new catalog on every run. Puppet
can be run with this enabled by default and then selectively disabled when a recompile is desired.
Default: false
use_srv_records
Whether the server will search for SRV records in DNS for the current domain.
Default: false
usecacheonfailure
Whether to use the cached conguration when the remote conguration will not compile. This
option is useful for testing new congurations, where you want to x the broken conguration
rather than reverting to a known-good one.
Default: true
Puppet 3.6 Reference Manual Conguration Reference 181/325
user
The user puppet master should run as.
Default: puppet
vardir
Where Puppet stores dynamic and growing data. The default for this setting is calculated specially,
like confdir_.
Default: /var/lib/puppet
waitforcert
How frequently puppet agent should ask for a signed certicate.
When starting for the rst time, puppet agent will submit a certicate signing request (CSR) to the
server named in the ca_server setting (usually the puppet master); this may be autosigned, or may
need to be approved by a human, depending on the CA servers conguration.
Puppet agent cannot apply congurations until its approved certicate is available. Since the
certicate may or may not be available immediately, puppet agent will repeatedly try to fetch it at
this interval. You can turn o waiting for certicates by specifying a time of 0, in which case puppet
agent will exit if it cannot get a cert. This setting can be a time interval in seconds (30 or 30s),
minutes (30m), hours (6h), days (2d), or years (5y).
Default: 2m
yamldir
The directory in which YAML data is stored, usually in a subdirectory.
Default: $vardir/yaml
zlib
Boolean; whether to use the zlib library
Default: true
This page autogenerated on 2014-06-12 11:06:27 -0700
Function Reference
Puppet 3.6 Reference Manual Function Reference 182/325
Function Reference
This page is autogenerated; any changes will get overwritten (last generated on 2014-06-12
11:06:36 -0700)
There are two types of functions in Puppet: Statements and rvalues. Statements stand on their own
and do not return arguments; they are used for performing stand-alone work like importing.
Rvalues return values and can only be used in a statement requiring a value, such as an assignment
or a case statement.
Functions execute on the Puppet master. They do not execute on the Puppet agent. Hence they only
have access to the commands and data available on the Puppet master host.
Here are the functions available in Puppet:
alert
Log a message on the server at level alert.
Type: statement
collect
The collect function has been renamed to map. Please update your manifests.
The collect function is reserved for future use. - Removed as of 3.4 - requires parser = future.
Type: rvalue
contain
Contain one or more classes inside the current class. If any of these classes are undeclared, they
will be declared as if called with the include function. Accepts a class name, an array of class
names, or a comma-separated list of class names.
A contained class will not be applied before the containing class is begun, and will be nished
before the containing class is nished.
Type: statement
create_resources
Converts a hash into a set of resources and adds them to the catalog.
This function takes two mandatory arguments: a resource type, and a hash describing a set of
resources. The hash should be in the form {title => {parameters} }:
Puppet 3.6 Reference Manual Function Reference 183/325
# A hash of user resources:
$myusers = {
'nick' => { uid => '1330',
gid => allstaff,
groups => ['developers', 'operations', 'release'], },
'dan' => { uid => '1308',
gid => allstaff,
groups => ['developers', 'prosvc', 'release'], },
}
create_resources(user, $myusers)
A third, optional parameter may be given, also as a hash:
$defaults = {
'ensure' => present,
'provider' => 'ldap',
}
create_resources(user, $myusers, $defaults)
The values given on the third argument are added to the parameters of each resource present in
the set given on the second argument. If a parameter is present on both the second and third
arguments, the one on the second argument takes precedence.
This function can be used to create dened resources and classes, as well as native resources.
Virtual and Exported resources may be created by prexing the type name with @ or @@
respectively. For example, the $myusers hash may be exported in the following manner:
create_resources("@@user", $myusers)
The $myusers may be declared as virtual resources using:
create_resources("@user", $myusers)
Type: statement
crit
Log a message on the server at level crit.
Type: statement
debug
Log a message on the server at level debug.
Puppet 3.6 Reference Manual Function Reference 184/325
Type: statement
dened
Determine whether a given class or resource type is dened. This function can also determine
whether a specic resource has been declared, or whether a variable has been assigned a value
(including undefas opposed to never having been assigned anything). Returns true or false.
Accepts class names, type names, resource references, and variable reference strings of the form
$name. When more than one argument is supplied, dened() returns true if any are dened.
The defined function checks both native and dened types, including types provided as plugins via
modules. Types and classes are both checked using their names:
defined("file")
defined("customtype")
defined("foo")
defined("foo::bar")
defined('$name')
Resource declarations are checked using resource references, e.g. defined( File['/tmp/myfile']
). Checking whether a given resource has been declared is, unfortunately, dependent on the parse
order of the conguration, and the following code will not work:
if defined(File['/tmp/foo']) {
notify { "This configuration includes the /tmp/foo file.":}
}
file { "/tmp/foo":
ensure => present,
}
However, this order requirement refers to parse order only, and ordering of resources in the
conguration graph (e.g. with before or require) does not aect the behavior of defined.
If the future parser is in eect, you may also search using types:
defined(Resource['file','/some/file'])
defined(File['/some/file'])
defined(Class['foo'])
Since 2.7.0
Since 3.6.0 variable reference and future parser types
Type: rvalue
Puppet 3.6 Reference Manual Function Reference 185/325
each
Applies a parameterized block to each element in a sequence of selected entries from the rst
argument and returns the rst argument.
This function takes two mandatory arguments: the rst should be an Array or a Hash or something
that is of enumerable type (integer, Integer range, or String), and the second a parameterized block
as produced by the puppet syntax:
$a.each |$x| { ... }
each($a) |$x| { ... }
When the rst argument is an Array (or of enumerable type other than Hash), the parameterized
block should dene one or two block parameters. For each application of the block, the next
element from the array is selected, and it is passed to the block if the block has one parameter. If
the block has two parameters, the rst is the elements index, and the second the value. The index
starts from 0.
$a.each |$index, $value| { ... }
each($a) |$index, $value| { ... }
When the rst argument is a Hash, the parameterized block should dene one or two parameters.
When one parameter is dened, the iteration is performed with each entry as an array of [key,
value], and when two parameters are dened the iteration is performed with key and value.
$a.each |$entry| { ..."key ${$entry[0]}, value ${$entry[1]}" }
$a.each |$key, $value| { ..."key ${key}, value ${value}" }
Examples
[1,2,3].each |$val| { ... } # 1, 2, 3
[5,6,7].each |$index, $val| { ... } # (0, 5), (1, 6), (2, 7)
{a=>1, b=>2, c=>3}].each |$val| { ... } # ['a', 1], ['b', 2], ['c',
3]
{a=>1, b=>2, c=>3}.each |$key, $val| { ... } # ('a', 1), ('b', 2), ('c',
3)
Integer[ 10, 20 ].each |$index, $value| { ... } # (0, 10), (1, 11) ...
"hello".each |$char| { ... } # 'h', 'e', 'l', 'l', 'o'
3.each |$number| { ... } # 0, 1, 2
Since 3.2 for Array and Hash
Since 3.5 for other enumerables
requires parser = future.
Puppet 3.6 Reference Manual Function Reference 186/325
Type: rvalue
emerg
Log a message on the server at level emerg.
Type: statement
epp
Evaluates an Embedded Puppet Template (EPP) le and returns the rendered text result as a String.
EPP support the following tags:
<%= puppet expression %> - This tag renders the value of the expression it contains.
<% puppet expression(s) %> - This tag will execute the expression(s) it contains, but renders
nothing.
<%# comment %> - The tag and its content renders nothing.
<%% or %%> - Renders a literal <% or %> respectively.
<%- - Same as <% but suppresses any leading whitespace.
-%> - Same as %> but suppresses any trailing whitespace on the same line (including line break).
<%-( parameters )-%> - When placed as the rst tag declares the templates parameters.
File based EPP supports the following visibilities of variables in scope:
Global scope (i.e. top + node scopes) - global scope is always visible
Global + all given arguments - if the EPP template does not declare parameters, and arguments
are given
Global + declared parameters - if the EPP declares parameters, given argument names must
match
EPP supports parameters by placing an optional parameter list as the very rst element in the EPP.
As an example, <%- ($x, $y, $z='unicorn') -%> when placed rst in the EPP text declares that
the parameters x and y must be given as template arguments when calling inline_epp, and that z
if not given as a template argument defaults to 'unicorn'. Template parameters are available as
variables, e.g.arguments $x, $y and $z in the example. Note that <%- must be used or any leading
whitespace will be interpreted as text
Arguments are passed to the template by calling epp with a Hash as the last argument, where
parameters are bound to values, e.g. epp('...', {'x'=>10, 'y'=>20}). Excess arguments may be
given (i.e. undeclared parameters) only if the EPP templates does not declare any parameters at all.
Template parameters shadow variables in outer scopes. File based epp does never have access to
variables in the scope where the epp function is called from.
Puppet 3.6 Reference Manual Function Reference 187/325
See function inline_epp for examples of EPP
Since 3.5
Requires Future Parser
Type: rvalue
err
Log a message on the server at level err.
Type: statement
extlookup
This is a parser function to read data from external les, this version uses CSV les but the concept
can easily be adjust for databases, yaml or any other queryable data source.
The object of this is to make it obvious when its being used, rather than magically loading data in
when a module is loaded I prefer to look at the code and see statements like:
$snmp_contact = extlookup("snmp_contact")
The above snippet will load the snmp_contact value from CSV les, this in its own is useful but a
common construct in puppet manifests is something like this:
case $domain {
"myclient.com": { $snmp_contact = "John Doe <[email protected]>" }
default: { $snmp_contact = "My Support <[email protected]>" }
}
Over time there will be a lot of this kind of thing spread all over your manifests and adding an
additional client involves grepping through manifests to nd all the places where you have
constructs like this.
This is a data problem and shouldnt be handled in code, and using this function you can do just
that.
First you congure it in site.pp:
$extlookup_datadir = "/etc/puppet/manifests/extdata"
$extlookup_precedence = ["%{fqdn}", "domain_%{domain}", "common"]
The array tells the code how to resolve values, rst it will try to nd it in web1.myclient.com.csv then
in domain_myclient.com.csv and nally in common.csv
Puppet 3.6 Reference Manual Function Reference 188/325
Now create the following data les in /etc/puppet/manifests/extdata:
domain_myclient.com.csv:
snmp_contact,John Doe <[email protected]>
root_contact,support@%{domain}
client_trusted_ips,192.168.1.130,192.168.10.0/24
common.csv:
snmp_contact,My Support <[email protected]>
root_contact,[email protected]
Now you can replace the case statement with the simple single line to achieve the exact same
outcome:
$snmp_contact = extlookup("snmp_contact")
The above code shows some other features, you can use any fact or variable that is in scope by
simply using %{varname} in your data les, you can return arrays by just having multiple values in
the csv after the initial variable name.
In the event that a variable is nowhere to be found a critical error will be raised that will prevent
your manifest from compiling, this is to avoid accidentally putting in empty values etc. You can
however specify a default value:
$ntp_servers = extlookup("ntp_servers", "1.${country}.pool.ntp.org")
In this case it will default to 1.${country}.pool.ntp.org if nothing is dened in any data le.
You can also specify an additional data le to search rst before any others at use time, for
example:
$version = extlookup("rsyslog_version", "present", "packages")
package{"rsyslog": ensure => $version }
This will look for a version congured in packages.csv and then in the rest as congured by
$extlookup_precedence if its not found anywhere it will default to present, this kind of use case
makes puppet a lot nicer for managing large amounts of packages since you do not need to edit a
load of manifests to do simple things like adjust a desired version number.
Precedence values can have variables embedded in them in the form %{fqdn}, you could for
example do:
$extlookup_precedence = ["hosts/%{fqdn}", "common"]
Puppet 3.6 Reference Manual Function Reference 189/325
This will result in /path/to/extdata/hosts/your.box.com.csv being searched.
This is for back compatibility to interpolate variables with %. % interpolation is a workaround for a
problem that has been xed: Puppet variable interpolation at top scope used to only happen on
each run.
Type: rvalue
fail
Fail with a parse error.
Type: statement
le
Return the contents of a le. Multiple les can be passed, and the rst le that exists will be read in.
Type: rvalue
lter
Applies a parameterized block to each element in a sequence of entries from the rst argument and
returns an array or hash (same type as left operand for array/hash, and array for other enumerable
types) with the entries for which the block evaluates to true.
This function takes two mandatory arguments: the rst should be an Array, a Hash, or an
Enumerable object (integer, Integer range, or String), and the second a parameterized block as
produced by the puppet syntax:
$a.filter |$x| { ... }
filter($a) |$x| { ... }
When the rst argument is something other than a Hash, the block is called with each entry in turn.
When the rst argument is a Hash the entry is an array with [key, value].
Examples
# selects all that end with berry
$a = ["raspberry", "blueberry", "orange"]
$a.filter |$x| { $x =~ /berry$/ } # rasberry, blueberry
If the block denes two parameters, they will be set to index, value (with index starting at 0) for
all enumerables except Hash, and to key, value for a Hash.
Examples
Puppet 3.6 Reference Manual Function Reference 190/325
# selects all that end with 'berry' at an even numbered index
$a = ["raspberry", "blueberry", "orange"]
$a.filter |$index, $x| { $index % 2 == 0 and $x =~ /berry$/ } # raspberry
# selects all that end with 'berry' and value >= 1
$a = {"raspberry"=>0, "blueberry"=>1, "orange"=>1}
$a.filter |$key, $x| { $x =~ /berry$/ and $x >= 1 } # blueberry
Since 3.4 for Array and Hash
Since 3.5 for other enumerables
requires parser = future
Type: rvalue
fqdn_rand
Usage: fqdn_rand(MAX, [SEED]). MAX is required and must be a positive integer; SEED is optional
and may be any number or string.
Generates a random whole number greater than or equal to 0 and less than MAX, combining the
$fqdn fact and the value of SEED for repeatable randomness. (That is, each node will get a dierent
random number from this function, but a given nodes result will be the same every time unless its
hostname changes.)
This function is usually used for spacing out runs of resource-intensive cron tasks that run on
many nodes, which could cause a thundering herd or degrade other services if they all re at once.
Adding a SEED can be useful when you have more than one such task and need several unrelated
random numbers per node. (For example, fqdn_rand(30), fqdn_rand(30, 'expensive job 1'),
and fqdn_rand(30, 'expensive job 2') will produce totally dierent numbers.)
Type: rvalue
generate
Calls an external command on the Puppet master and returns the results of the command. Any
arguments are passed to the external command as arguments. If the generator does not exit with
return code of 0, the generator is considered to have failed and a parse error is thrown. Generators
can only have le separators, alphanumerics, dashes, and periods in them. This function will
attempt to protect you from malicious generator calls (e.g., those with .. in them), but it can never
be entirely safe. No subshell is used to execute generators, so all shell metacharacters are passed
directly to the generator.
Type: rvalue
hiera
Puppet 3.6 Reference Manual Function Reference 191/325
Performs a standard priority lookup and returns the most specic value for a given key. The
returned value can be data of any type (strings, arrays, or hashes).
In addition to the required key argument, hiera accepts two additional arguments:
a default argument in the second position, providing a value to be returned in the absence of
matches to the key argument
an override argument in the third position, providing a data source to consult for matching
values, even if it would not ordinarily be part of the matched hierarchy. If Hiera doesnt nd a
matching key in the named override data source, it will continue to search through the rest of
the hierarchy.
More thorough examples of hiera are available at:
http://docs.puppetlabs.com/hiera/1/puppet.html#hiera-lookup-functions
Type: rvalue
hiera_array
Returns all matches throughout the hierarchy not just the rst match as a attened array of
unique values. If any of the matched values are arrays, theyre attened and included in the results.
In addition to the required key argument, hiera_array accepts two additional arguments:
a default argument in the second position, providing a string or array to be returned in the
absence of matches to the key argument
an override argument in the third position, providing a data source to consult for matching
values, even if it would not ordinarily be part of the matched hierarchy. If Hiera doesnt nd a
matching key in the named override data source, it will continue to search through the rest of
the hierarchy.
If any matched value is a hash, puppet will raise a type mismatch error.
More thorough examples of hiera are available at:
http://docs.puppetlabs.com/hiera/1/puppet.html#hiera-lookup-functions
Type: rvalue
hiera_hash
Returns a merged hash of matches from throughout the hierarchy. In cases where two or more
hashes share keys, the hierarchy order determines which key/value pair will be used in the returned
hash, with the pair in the highest priority data source winning.
In addition to the required key argument, hiera_hash accepts two additional arguments:
Puppet 3.6 Reference Manual Function Reference 192/325
a default argument in the second position, providing a hash to be returned in the absence of
any matches for the key argument
an override argument in the third position, providing a data source to insert at the top of the
hierarchy, even if it would not ordinarily match during a Hiera data source lookup. If Hiera
doesnt nd a match in the named override data source, it will continue to search through the
rest of the hierarchy.
hiera_hash expects that all values returned will be hashes. If any of the values found in the data
sources are strings or arrays, puppet will raise a type mismatch error.
More thorough examples of hiera_hash are available at:
http://docs.puppetlabs.com/hiera/1/puppet.html#hiera-lookup-functions
Type: rvalue
hiera_include
Assigns classes to a node using an array merge lookup that retrieves the value for a user-specied
key from a Hiera data source.
To use hiera_include, the following conguration is required:
A key name to use for classes, e.g. classes.
A line in the puppet sites.pp le (e.g. /etc/puppet/manifests/sites.pp) reading
hiera_include('classes'). Note that this line must be outside any node denition and below
any top-scope variables in use for Hiera lookups.
Class keys in the appropriate data sources. In a data source keyed to a nodes role, one might
have:
---
classes:
- apache
- apache::passenger
In addition to the required key argument, hiera_include accepts two additional arguments:
a default argument in the second position, providing an array to be returned in the absence of
matches to the key argument
an override argument in the third position, providing a data source to consult for matching
values, even if it would not ordinarily be part of the matched hierarchy. If Hiera doesnt nd a
matching key in the named override data source, it will continue to search through the rest of
the hierarchy.
More thorough examples of hiera_include are available at:
Puppet 3.6 Reference Manual Function Reference 193/325
http://docs.puppetlabs.com/hiera/1/puppet.html#hiera-lookup-functions
Type: statement
include
Declares one or more classes, causing the resources in them to be evaluated and added to the
catalog. Accepts a class name, an array of class names, or a comma-separated list of class names.
The include function can be used multiple times on the same class and will only declare a given
class once. If a class declared with include has any parameters, Puppet will automatically look up
values for them in Hiera, using <class name>::<parameter name> as the lookup key.
Contrast this behavior with resource-like class declarations ( class {'name': parameter =>
'value',}), which must be used in only one place per class and can directly set parameters. You
should avoid using both include and resource-like declarations with the same class.
The include function does not cause classes to be contained in the class where they are declared.
For that, see the contain function. It also does not create a dependency relationship between the
declared class and the surrounding class; for that, see the require function.
Type: statement
info
Log a message on the server at level info.
Type: statement
inline_epp
Evaluates an Embedded Puppet Template (EPP) string and returns the rendered text result as a
String.
EPP support the following tags:
<%= puppet expression %> - This tag renders the value of the expression it contains.
<% puppet expression(s) %> - This tag will execute the expression(s) it contains, but renders
nothing.
<%# comment %> - The tag and its content renders nothing.
<%% or %%> - Renders a literal <% or %> respectively.
<%- - Same as <% but suppresses any leading whitespace.
-%> - Same as %> but suppresses any trailing whitespace on the same line (including line break).
<%-( parameters )-%> - When placed as the rst tag declares the templates parameters.
Puppet 3.6 Reference Manual Function Reference 194/325
Inline EPP supports the following visibilities of variables in scope which depends on how EPP
parameters are used - see further below:
Global scope (i.e. top + node scopes) - global scope is always visible
Global + Enclosing scope - if the EPP template does not declare parameters, and no arguments
are given
Global + all given arguments - if the EPP template does not declare parameters, and arguments
are given
Global + declared parameters - if the EPP declares parameters, given argument names must
match
EPP supports parameters by placing an optional parameter list as the very rst element in the EPP.
As an example, <%-( $x, $y, $z='unicorn' )-%> when placed rst in the EPP text declares that
the parameters x and y must be given as template arguments when calling inline_epp, and that z
if not given as a template argument defaults to 'unicorn'. Template parameters are available as
variables, e.g.arguments $x, $y and $z in the example. Note that <%- must be used or any leading
whitespace will be interpreted as text
Arguments are passed to the template by calling inline_epp with a Hash as the last argument,
where parameters are bound to values, e.g. inline_epp('...', {'x'=>10, 'y'=>20}). Excess
arguments may be given (i.e. undeclared parameters) only if the EPP templates does not declare any
parameters at all. Template parameters shadow variables in outer scopes.
Note: An inline template is best stated using a single-quoted string, or a heredoc since a double-
quoted string is subject to expression interpolation before the string is parsed as an EPP template.
Here are examples (using heredoc to dene the EPP text):
# produces 'Hello local variable world!'
$x ='local variable'
inline_epptemplate(@(END:epp))
<%-( $x )-%>
Hello <%= $x %> world!
END
# produces 'Hello given argument world!'
$x ='local variable world'
inline_epptemplate(@(END:epp), { x =>'given argument'})
<%-( $x )-%>
Hello <%= $x %> world!
END
# produces 'Hello given argument world!'
$x ='local variable world'
inline_epptemplate(@(END:epp), { x =>'given argument'})
<%-( $x )-%>
Hello <%= $x %>!
END
Puppet 3.6 Reference Manual Function Reference 195/325
# results in error, missing value for y
$x ='local variable world'
inline_epptemplate(@(END:epp), { x =>'given argument'})
<%-( $x, $y )-%>
Hello <%= $x %>!
END
# Produces 'Hello given argument planet'
$x ='local variable world'
inline_epptemplate(@(END:epp), { x =>'given argument'})
<%-( $x, $y=planet)-%>
Hello <%= $x %> <%= $y %>!
END
Since 3.5
Requires Future Parser
Type: rvalue
inline_template
Evaluate a template string and return its value. See the templating docs for more information. Note
that if multiple template strings are specied, their output is all concatenated and returned as the
output of the function.
Type: rvalue
lookup
Looks up data dened using Puppet Bindings and Hiera. The function is callable with one to three
arguments and optionally with a code block to further process the result.
The lookup function can be called in one of these ways:
lookup(name)
lookup(name, type)
lookup(name, type, default)
lookup(options_hash)
lookup(name, options_hash)
The function may optionally be called with a code block / lambda with the following signatures:
lookup(...) |$result| { ... }
lookup(...) |$name, $result| { ... }
lookup(...) |$name, $result, $default| { ... }
The longer signatures are useful when the block needs to raise an error (it can report the name), or
if it needs to know if the given default value was selected.
Puppet 3.6 Reference Manual Function Reference 196/325
The code block receives the following three arguments:
The $name is the last name that was looked up (the name if only one name was looked up)
The $result is the looked up value (or the default value if not found).
The $default is the given default value ( undef if not given).
The block, if present, is called with the result from the lookup. The value produced by the block is
also what is produced by the lookup function. When a block is used, it is the users responsibility to
call error if the result does not meet additional criteria, or if an undef value is not acceptable. If a
value is not found, and a default has been specied, the default value is given to the block.
The content of the options hash is:
name - The name or array of names to lookup (rst found is returned)
type - The type to assert (a Type or a type specication in string form)
default - The default value if there was no value found (must comply with the data type)
accept_undef - (default false) An undef result is accepted if this options is set to true.
override - a hash with map from names to values that are used instead of the underlying
bindings. If the name is found here it wins. Defaults to an empty hash.
extra - a hash with map from names to values that are used as a last resort to obtain a value.
Defaults to an empty hash.
When the call is on the form lookup(name, options_hash), or lookup(name, type,
options_hash), the given name argument wins over the options_hash['name'].
The search order is override (if given), then binder, then hiera and nally extra (if given). The
rst to produce a value other than undef for a given name wins.
The type specication is one of:
A type in the Puppet Type System, e.g.:
Integer, an integral value with optional range e.g.:
Integer[0, default] - 0 or positive
Integer[default, -1] - negative,
Integer[1,100] - value between 1 and 100 inclusive
String- any string
Float - oating point number (same signature as for Integer for Integer ranges)
Boolean - true of false (strict)
Array - an array (of Data by default), or parameterized as Array[<element_type>], where
Puppet 3.6 Reference Manual Function Reference 197/325
<element_type> is the expected type of elements
Hash, - a hash (of default Literal keys and Data values), or parameterized as
Hash[<value_type>], Hash[<key_type>, <value_type>], where <key_type>, and
<value_type> are the types of the keys and values respectively (key is Literal by default).
Data - abstract type representing any Literal, Array[Data], or Hash[Literal, Data]
Pattern[<p1>, <p2>, ..., <pn>] - an enumeration of valid patterns (one or more) where a
pattern is a regular expression string or regular expression, e.g. Pattern['.com$',
'.net$'], Pattern[/[a-z]+[0-9]+/]
Enum[<s1>, <s2>, ..., <sn>], - an enumeration of exact string values (one or more) e.g.
Enum[blue, red, green].
Variant[<t1>, <t2>,...<tn>] - matches one of the listed types (at least one must be given)
e.g. Variant[Integer[8000,8999], Integer[20000, 99999]] to accept a value in either
range
Regexp- a regular expression (i.e. the result is a regular expression, not a string matching a
regular expression).
A string containing a type description - one of the types as shown above but in string form.
If the function is called without specifying a default value, and nothing is bound to the given name
an error is raised unless the option accept_undef is true. If a block is given it must produce an
acceptable value (or call error). If the block does not produce an acceptable value an error is
raised.
Examples:
When called with one argument; the name, it returns the bound value with the given name after
having asserted it has the default datatype Data:
lookup('the_name')
When called with two arguments; the name, and the expected type, it returns the bound value with
the given name after having asserted it has the given data type (String in the example):
lookup('the_name', 'String') # 3.x
lookup('the_name', String) # parser future
When called with three arguments, the name, the expected type, and a default, it returns the bound
value with the given name, or the default after having asserted the value has the given data type
( String in the example above):
Puppet 3.6 Reference Manual Function Reference 198/325
lookup('the_name', 'String', 'Fred') # 3x
lookup('the_name', String, 'Fred') # parser future
Using a lambda to process the looked up result - asserting that it starts with an upper case letter:
# only with parser future
lookup('the_size', Integer[1,100]) |$result| {
if $large_value_allowed and $result > 10
{ error 'Values larger than 10 are not allowed'}
$result
}
Including the name in the error
# only with parser future
lookup('the_size', Integer[1,100]) |$name, $result| {
if $large_value_allowed and $result > 10
{ error 'The bound value for '${name}' can not be larger than 10 in this
configuration'}
$result
}
When using a block, the value it produces is also asserted against the given type, and it may not be
undef unless the option 'accept_undef' is true.
All options work as the corresponding (direct) argument. The first_found option and
accept_undef are however only available as options.
Using rst_found semantics option to return the rst name that has a bound value:
lookup(['apache::port', 'nginx::port'], 'Integer', 80)
If you want to make lookup return undef when no value was found instead of raising an error:
$are_you_there = lookup('peekaboo', { accept_undef => true} )
$are_you_there = lookup('peekaboo', { accept_undef => true}) |$result| {
$result }
Type: rvalue
map
Applies a parameterized block to each element in a sequence of entries from the rst argument and
returns an array with the result of each invocation of the parameterized block.
This function takes two mandatory arguments: the rst should be an Array, Hash, or of Enumerable
Puppet 3.6 Reference Manual Function Reference 199/325
type (integer, Integer range, or String), and the second a parameterized block as produced by the
puppet syntax:
$a.map |$x| { ... }
map($a) |$x| { ... }
When the rst argument $a is an Array or of enumerable type, the block is called with each entry in
turn. When the rst argument is a hash the entry is an array with [key, value].
Examples
# Turns hash into array of values
$a.map |$x|{ $x[1] }
# Turns hash into array of keys
$a.map |$x| { $x[0] }
When using a block with 2 parameters, the elements index (starting from 0) for an array, and the
key for a hash is given to the blocks rst parameter, and the value is given to the blocks second
parameter.args.
Examples
# Turns hash into array of values
$a.map |$key,$val|{ $val }
# Turns hash into array of keys
$a.map |$key,$val|{ $key }
Since 3.4 for Array and Hash
Since 3.5 for other enumerables, and support for blocks with 2 parameters
requires parser = future
Type: rvalue
md5
Returns a MD5 hash value from a provided string.
Type: rvalue
notice
Log a message on the server at level notice.
Type: statement
Puppet 3.6 Reference Manual Function Reference 200/325
realize
Make a virtual object real. This is useful when you want to know the name of the virtual object and
dont want to bother with a full collection. It is slightly faster than a collection, and, of course, is a
bit shorter. You must pass the object using a reference; e.g.: realize User[luke].
Type: statement
reduce
Applies a parameterized block to each element in a sequence of entries from the rst argument
(the enumerable) and returns the last result of the invocation of the parameterized block.
This function takes two mandatory arguments: the rst should be an Array, Hash, or something of
enumerable type, and the last a parameterized block as produced by the puppet syntax:
$a.reduce |$memo, $x| { ... }
reduce($a) |$memo, $x| { ... }
When the rst argument is an Array or someting of an enumerable type, the block is called with
each entry in turn. When the rst argument is a hash each entry is converted to an array with [key,
value] before being fed to the block. An optional start memo value may be supplied as an
argument between the array/hash and mandatory block.
$a.reduce(start) |$memo, $x| { ... }
reduce($a, start) |$memo, $x| { ... }
If no start memo is given, the rst invocation of the parameterized block will be given the rst and
second elements of the enumeration, and if the enumerable has fewer than 2 elements, the rst
element is produced as the result of the reduction without invocation of the block.
On each subsequent invocation, the produced value of the invoked parameterized block is given as
the memo in the next invocation.
Examples
# Reduce an array
$a = [1,2,3]
$a.reduce |$memo, $entry| { $memo + $entry }
#=> 6
# Reduce hash values
$a = {a => 1, b => 2, c => 3}
$a.reduce |$memo, $entry| { [sum, $memo[1]+$entry[1]] }
#=> [sum, 6]
Puppet 3.6 Reference Manual Function Reference 201/325
# reverse a string
"abc".reduce |$memo, $char| { "$char$memo" }
#=>"cbe"
It is possible to provide a starting memo as an argument.
Examples
# Reduce an array
$a = [1,2,3]
$a.reduce(4) |$memo, $entry| { $memo + $entry }
#=> 10
# Reduce hash values
$a = {a => 1, b => 2, c => 3}
$a.reduce([na, 4]) |$memo, $entry| { [sum, $memo[1]+$entry[1]] }
#=> [sum, 10]
Examples
Integer[1,4].reduce |$memo, $x| { $memo + $x }
#=> 10
Since 3.2 for Array and Hash
Since 3.5 for additional enumerable types
requires parser = future.
Type: rvalue
regsubst
Perform regexp replacement on a string or array of strings.
Parameters (in order):
target The string or array of strings to operate on. If an array, the replacement will be
performed on each of the elements in the array, and the return value will be an array.
regexp The regular expression matching the target string. If you want it anchored at the start
and or end of the string, you must do that with ^ and $ yourself.
replacement Replacement string. Can contain backreferences to what was matched using \0
(whole match), \1 (rst set of parentheses), and so on.
agsOptional. String of single letter ags for how the regexp is interpreted:
E Extended regexps
I Ignore case in regexps
M Multiline regexps
G Global replacement; all occurrences of the regexp in each target string will be replaced.
Without this, only the rst occurrence will be replaced.
Puppet 3.6 Reference Manual Function Reference 202/325
encoding Optional. How to handle multibyte characters. A single-character string with the
following values:
N None
E EUC
S SJIS
U UTF-8
Examples
Get the third octet from the nodes IP address:
$i3 = regsubst($ipaddress,'^(\d+)\.(\d+)\.(\d+)\.(\d+)$','\3')
Put angle brackets around each octet in the nodes IP address:
$x = regsubst($ipaddress, '([0-9]+)', '<\1>', 'G')
Type: rvalue
require
Evaluate one or more classes, adding the required class as a dependency.
The relationship metaparameters work well for specifying relationships between individual
resources, but they can be clumsy for specifying relationships between classes. This function is a
superset of the include function, adding a class relationship so that the requiring class depends
on the required class.
Warning: using require in place of include can lead to unwanted dependency cycles.
For instance the following manifest, with require instead of include would produce a nasty
dependence cycle, because notify imposes a before between File[/foo] and Service[foo]:
class myservice {
service { foo: ensure => running }
}
class otherstuff {
include myservice
file { '/foo': notify => Service[foo] }
}
Note that this function only works with clients 0.25 and later, and it will fail if used with earlier
clients.
Puppet 3.6 Reference Manual Function Reference 203/325
Type: statement
search
Add another namespace for this class to search. This allows you to create classes with sets of
denitions and add those classes to another classs search path.
Type: statement
select
The select function has been renamed to lter. Please update your manifests.
The select function is reserved for future use. - Removed as of 3.4 - requires parser = future.
Type: rvalue
sha1
Returns a SHA1 hash value from a provided string.
Type: rvalue
shellquote
Quote and concatenate arguments for use in Bourne shell.
Each argument is quoted separately, and then all are concatenated with spaces. If an argument is
an array, the elements of that array is interpolated within the rest of the arguments; this makes it
possible to have an array of arguments and pass that array to shellquote instead of having to
specify each argument individually in the call.
Type: rvalue
slice
Applies a parameterized block to each slice of elements in a sequence of selected entries from the
rst argument and returns the rst argument, or if no block is given returns a new array with a
concatenation of the slices.
This function takes two mandatory arguments: the rst, $a, should be an Array, Hash, or something
of enumerable type (integer, Integer range, or String), and the second, $n, the number of elements
to include in each slice. The optional third argument should be a a parameterized block as
produced by the puppet syntax:
$a.slice($n) |$x| { ... }
slice($a) |$x| { ... }
Puppet 3.6 Reference Manual Function Reference 204/325
The parameterized block should have either one parameter (receiving an array with the slice), or
the same number of parameters as specied by the slice size (each parameter receiving its part of
the slice). In case there are fewer remaining elements than the slice size for the last slice it will
contain the remaining elements. When the block has multiple parameters, excess parameters are
set to :undef for an array or enumerable type, and to empty arrays for a Hash.
$a.slice(2) |$first, $second| { ... }
When the rst argument is a Hash, each key,value entry is counted as one, e.g, a slice size of 2 will
produce an array of two arrays with key, and value.
$a.slice(2) |$entry| { notice "first ${$entry[0]}, second
${$entry[1]}" }
$a.slice(2) |$first, $second| { notice "first ${first}, second ${second}" }
When called without a block, the function produces a concatenated result of the slices.
slice([1,2,3,4,5,6], 2) # produces [[1,2], [3,4], [5,6]]
slice(Integer[1,6], 2) # produces [[1,2], [3,4], [5,6]]
slice(4,2) # produces [[0,1], [2,3]]
slice('hello',2) # produces [[h, e], [l, l], [o]]
Since 3.2 for Array and Hash
Since 3.5 for additional enumerable types
requires parser = future.
Type: rvalue
split
Split a string variable into an array using the specied split regexp.
Example:
$string = 'v1.v2:v3.v4'
$array_var1 = split($string, ':')
$array_var2 = split($string, '[.]')
$array_var3 = split($string, '[.:]')
$array_var1 now holds the result ['v1.v2', 'v3.v4'], while $array_var2 holds ['v1',
'v2:v3', 'v4'], and $array_var3 holds ['v1', 'v2', 'v3', 'v4'].
Note that in the second example, we split on a literal string that contains a regexp meta-character
Puppet 3.6 Reference Manual Function Reference 205/325
(.), which must be escaped. A simple way to do that for a single character is to enclose it in square
brackets; a backslash will also escape a single character.
Type: rvalue
sprintf
Perform printf-style formatting of text.
The rst parameter is format string describing how the rest of the parameters should be formatted.
See the documentation for the Kernel::sprintf function in Ruby for all the details.
Type: rvalue
tag
Add the specied tags to the containing class or denition. All contained objects will then acquire
that tag, also.
Type: statement
tagged
A boolean function that tells you whether the current container is tagged with the specied tags.
The tags are ANDed, so that all of the specied tags must be included for the function to return
true.
Type: rvalue
template
Evaluate a template and return its value. See the templating docs for more information.
Note that if multiple templates are specied, their output is all concatenated and returned as the
output of the function.
Type: rvalue
versioncmp
Compares two version numbers.
Prototype:
$result = versioncmp(a, b)
Where a and b are arbitrary version strings.
Puppet 3.6 Reference Manual Function Reference 206/325
This function returns:
1 if version a is greater than version b
0 if the versions are equal
-1 if version a is less than version b
Example:
if versioncmp('2.6-1', '2.4.5') > 0 {
notice('2.6-1 is > than 2.4.5')
}
This function uses the same version comparison algorithm used by Puppets package type.
Type: rvalue
warning
Log a message on the server at level warning.
Type: statement
This page autogenerated on 2014-06-12 11:06:36 -0700
Metaparameter Reference
Puppet 3.6 Reference Manual Metaparameter Reference 207/325
Metaparameter Reference
This page is autogenerated; any changes will get overwritten (last generated on 2014-06-12
11:06:55 -0700)
Puppet 3.6 Reference Manual Metaparameter Reference 208/325
Metaparameters
Metaparameters are parameters that work with any resource type; they are part of the Puppet
framework itself rather than being part of the implementation of any given instance. Thus, any
dened metaparameter can be used with any instance in your manifest, including dened
components.
Available Metaparameters
alias
Creates an alias for the resource. Puppet uses this internally when you provide a symbolic title and
an explicit namevar value:
file { 'sshdconfig':
path => $operatingsystem ? {
solaris => '/usr/local/etc/ssh/sshd_config',
default => '/etc/ssh/sshd_config',
},
source => '...'
}
service { 'sshd':
subscribe => File['sshdconfig'],
}
When you use this feature, the parser sets sshdconfig as the title, and the library sets that as an
alias for the le so the dependency lookup in Service['sshd'] works. You can use this
metaparameter yourself, but note that aliases generally only work for creating relationships;
anything else that refers to an existing resource (such as amending or overriding resource
attributes in an inherited class) must use the resources exact title. For example, the following code
will not work:
file { '/etc/ssh/sshd_config':
owner => root,
group => root,
alias => 'sshdconfig',
}
File['sshdconfig'] {
mode => 644,
}
Theres no way here for the Puppet parser to know that these two stanzas should be aecting the
same le.
Puppet 3.6 Reference Manual Metaparameters 209/325
audit
Marks a subset of this resources unmanaged attributes for auditing. Accepts an attribute name, an
array of attribute names, or all.
Auditing a resource attribute has two eects: First, whenever a catalog is applied with puppet apply
or puppet agent, Puppet will check whether that attribute of the resource has been modied,
comparing its current value to the previous run; any change will be logged alongside any actions
performed by Puppet while applying the catalog.
Secondly, marking a resource attribute for auditing will include that attribute in inspection reports
generated by puppet inspect; see the puppet inspect documentation for more details.
Managed attributes for a resource can also be audited, but note that changes made by Puppet will
be logged as additional modications. (I.e. if a user manually edits a le whose contents are audited
and managed, puppet agents next two runs will both log an audit notice: the rst run will log the
users edit and then revert the le to the desired state, and the second run will log the edit made by
Puppet.)
before
One or more resources that depend on this resource, expressed as resource references. Multiple
resources can be specied as an array of references. When this attribute is present:
This resource will be applied before the dependent resource(s).
This is one of the four relationship metaparameters, along with require, notify, and subscribe.
For more context, including the alternate chaining arrow ( -> and ~>) syntax, see the language
page on relationships.
loglevel
Sets the level that information will be logged. The log levels have the biggest impact when logs are
sent to syslog (which is currently the default).
Valid values are debug, info, notice, warning, err, alert, emerg, crit, verbose.
noop
Whether to apply this resource in noop mode.
When applying a resource in noop mode, Puppet will check whether it is in sync, like it does when
running normally. However, if a resource attribute is not in the desired state (as declared in the
catalog), Puppet will take no action, and will instead report the changes it would have made. These
simulated changes will appear in the report sent to the puppet master, or be shown on the console
if running puppet agent or puppet apply in the foreground. The simulated changes will not send
refresh events to any subscribing or notied resources, although Puppet will log that a refresh
event would have been sent.
Puppet 3.6 Reference Manual Metaparameters 210/325
Important note: The noop setting allows you to globally enable or disable noop mode, but it will not
override the noop metaparameter on individual resources. That is, the value of the global noop
setting will only aect resources that do not have an explicit value set for their noop attribute.
Valid values are true, false.
notify
One or more resources that depend on this resource, expressed as resource references. Multiple
resources can be specied as an array of references. When this attribute is present:
This resource will be applied before the notied resource(s).
If Puppet makes changes to this resource, it will cause all of the notied resources to refresh.
(Refresh behavior varies by resource type: services will restart, mounts will unmount and re-
mount, etc. Not all types can refresh.)
This is one of the four relationship metaparameters, along with before, require, and subscribe.
For more context, including the alternate chaining arrow ( -> and ~>) syntax, see the language
page on relationships.
require
One or more resources that this resource depends on, expressed as resource references. Multiple
resources can be specied as an array of references. When this attribute is present:
The required resource(s) will be applied before this resource.
This is one of the four relationship metaparameters, along with before, notify, and subscribe.
For more context, including the alternate chaining arrow ( -> and ~>) syntax, see the language
page on relationships.
schedule
A schedule to govern when Puppet is allowed to manage this resource. The value of this
metaparameter must be the name of a schedule resource. This means you must declare a schedule
resource, then refer to it by name; see the docs for the schedule type for more info.
schedule { 'everyday':
period => daily,
range => "2-4"
}
exec { "/usr/bin/apt-get update":
schedule => 'everyday'
}
Note that you can declare the schedule resource anywhere in your manifests, as long as it ends up
Puppet 3.6 Reference Manual Metaparameters 211/325
in the nal compiled catalog.
stage
Which run stage this class should reside in.
Note: This metaparameter can only be used on classes, and only when declaring them with the
resource-like syntax. It cannot be used on normal resources or on classes declared with include.
By default, all classes are declared in the main stage. To assign a class to a dierent stage, you
must:
Declare the new stage as a stage resource.
Declare an order relationship between the new stage and the main stage.
Use the resource-like syntax to declare the class, and set the stage metaparameter to the name
of the desired stage.
For example:
stage { 'pre':
before => Stage['main'],
}
class { 'apt-updates':
stage => 'pre',
}
subscribe
One or more resources that this resource depends on, expressed as resource references. Multiple
resources can be specied as an array of references. When this attribute is present:
The subscribed resource(s) will be applied before this resource.
If Puppet makes changes to any of the subscribed resources, it will cause this resource to
refresh. (Refresh behavior varies by resource type: services will restart, mounts will unmount and
re-mount, etc. Not all types can refresh.)
This is one of the four relationship metaparameters, along with before, require, and notify. For
more context, including the alternate chaining arrow ( -> and ~>) syntax, see the language page on
relationships.
tag
Add the specied tags to the associated resource. While all resources are automatically tagged with
as much information as possible (e.g., each class and denition containing the resource), it can be
useful to add your own tags to a given resource.
Puppet 3.6 Reference Manual Metaparameters 212/325
Multiple tags can be specied as an array:
file {'/etc/hosts':
ensure => file,
source => 'puppet:///modules/site/hosts',
mode => 0644,
tag => ['bootstrap', 'minimumrun', 'mediumrun'],
}
Tags are useful for things like applying a subset of a hosts conguration with the tags setting (e.g.
puppet agent --test --tags bootstrap) or ltering alerts with the tagmail report processor.
This page autogenerated on 2014-06-12 11:06:58 -0700
Report Reference
Puppet 3.6 Reference Manual Report Reference 213/325
Report Reference
This page is autogenerated; any changes will get overwritten (last generated on 2014-06-12
11:07:06 -0700)
Puppet clients can report back to the server after each transaction. This transaction report is sent as
a YAML dump of the Puppet::Transaction::Report class and includes every log message that was
generated during the transaction along with as many metrics as Puppet knows how to collect. See
Reports and Reporting for more information on how to use reports.
Currently, clients default to not sending in reports; you can enable reporting by setting the report
parameter to true.
To use a report, set the reports parameter on the server; multiple reports must be comma-
separated. You can also specify none to disable reports entirely.
Puppet provides multiple report handlers that will process client reports:
http
Send reports via HTTP or HTTPS. This report processor submits reports as POST requests to the
address in the reporturl setting. The body of each POST request is the YAML dump of a
Puppet::Transaction::Report object, and the Content-Type is set as application/x-yaml.
log
Send all received logs to the local log destinations. Usually the log destination is syslog.
rrdgraph
Graph all available data about hosts using the RRD library. You must have the Ruby RRDtool library
installed to use this report, which you can get from the RubyRRDTool RubyForge page. This
package may also be available as librrd-ruby, ruby-rrd, or rrdtool-ruby in your distributions
package management system. The library and/or package will both require the binary rrdtool
package from your distribution to be installed.
This report will create, manage, and graph RRD database les for each of the metrics generated
during transactions, and it will create a few simple html les to display the reporting hosts graphs.
At this point, it will not create a common index le to display links to all hosts.
All RRD les and graphs get created in the rrddir directory. If you want to serve these publicly, you
should be able to just alias that directory in a web server.
If you really know what youre doing, you can tune the rrdinterval, which defaults to the
Puppet 3.6 Reference Manual Report Reference 214/325
runinterval.
store
Store the yaml report on disk. Each host sends its report as a YAML dump and this just stores the
le on disk, in the reportdir directory.
These les collect quickly one every half hour so it is a good idea to perform some maintenance
on them if you use this report (its the only default report).
tagmail
This report sends specic log messages to specic email addresses based on the tags in the log
messages.
See the documentation on tags for more information.
To use this report, you must create a tagmail.conf le in the location specied by the tagmap
setting. This is a simple le that maps tags to email addresses: Any log messages in the report that
match the specied tags will be sent to the specied email addresses.
Lines in the tagmail.conf le consist of a comma-separated list of tags, a colon, and a comma-
separated list of email addresses. Tags can be !negated with a leading exclamation mark, which will
subtract any messages with that tag from the set of events handled by that line.
Puppets log levels ( debug, info, notice, warning, err, alert, emerg, crit, and verbose) can also
be used as tags, and there is an all tag that will always match all log messages.
An example tagmail.conf:
all: [email protected]
webserver, !mailserver: [email protected]
This will send all messages to [email protected], and all messages from webservers that are not also
from mailservers to [email protected].
If you are using anti-spam controls such as grey-listing on your mail server, you should whitelist
the sending email address (controlled by reportfrom conguration option) to ensure your email is
not discarded as spam.
This page autogenerated on 2014-06-12 11:07:06 -0700
Indirection Reference
Puppet 3.6 Reference Manual Indirection Reference 215/325
Puppet 3.6 Reference Manual Indirection Reference 216/325
Indirection Reference
This page is autogenerated; any changes will get overwritten (last generated on 2014-06-12
11:06:44 -0700)
About Indirection
Puppets indirector support pluggable backends (termini) for a variety of key-value stores
(indirections). Each indirection type corresponds to a particular Ruby class (the Indirected Class
below) and values are instances of that class. Each instances key is available from its name method.
The termini can be local (e.g., on-disk les) or remote (e.g., using a REST interface to talk to a
puppet master).
An indirector has ve methods, which are mapped into HTTP verbs for the REST interface:
find(key) - get a single value (mapped to GET or POST with a singular endpoint)
search(key) - get a list of matching values (mapped to GET with a plural endpoint)
head(key) - return true if the key exists (mapped to HEAD)
destroy(key) - remove the key van value (mapped to DELETE)
save(instance) - write the instance to the store, using the instances name as the key (mapped
to PUT)
These methods are available via the indirection class method on the indirected classes. For
example:
foo_cert = Puppet::SSL::Certificate.indirection.find('foo.example.com')
At startup, each indirection is congured with a terminus. In most cases, this is the default terminus
dened by the indirected class, but it can be overridden by the application or face, or overridden
with the route_file conguration. The available termini dier for each indirection, and are listed
below.
Indirections can also have a cache, represented by a second terminus. This is a write-through
cache: modications are written both to the cache and to the primary terminus. Values fetched from
the terminus are written to the cache.
Interaction with REST
REST endpoints have the form /{environment}/{indirection}/{key}, where the indirection can
be singular or plural, following normal English spelling rules. On the server side, REST responses
are generated from the locally-congured endpoints.
Puppet 3.6 Reference Manual Indirection Reference 217/325
Indirections and Termini
Below is the list of all indirections, their associated terminus classes, and how you select between
them.
In general, the appropriate terminus class is selected by the application for you (e.g., puppet agent
would always use the rest terminus for most of its indirected classes), but some classes are
tunable via normal settings. These will have terminus setting documentation listed with them.
catalog
Indirected Class: Puppet::Resource::Catalog
Terminus Setting: catalog_terminus
active_record terminus
A component of ActiveRecord storecongs. ActiveRecord-based storecongs and inventory are
deprecated. See http://links.puppetlabs.com/activerecord-deprecation
compiler terminus
Compiles catalogs on demand using Puppets compiler.
json terminus
Store catalogs as at les, serialized using JSON.
msgpack terminus
Store catalogs as at les, serialized using MessagePack.
queue terminus
Part of async storecongs, requiring the puppet queue daemon. ActiveRecord-based storecongs
and inventory are deprecated. See http://links.puppetlabs.com/activerecord-deprecation
rest terminus
Find resource catalogs over HTTP via REST.
static_compiler terminus
Compiles catalogs on demand using the optional static compiler. This functions similarly to the
normal compiler, but it replaces puppet:/// le URLs with explicit metadata and le content hashes,
expecting puppet agent to fetch the exact specied content from the lebucket. This guarantees
that a given catalog will always result in the same le states. It also decreases catalog application
time and leserver load, at the cost of increased compilation time.
This terminus works today, but cannot be used without additional conguration. Specically:
Puppet 3.6 Reference Manual Indirection Reference 218/325
You must create a special lebucket resource with the title puppet and the path attribute set
to false in site.pp or somewhere else where it will be added to every nodes catalog. Using
puppet as the title is mandatory; the static compiler treats this title as magical.
filebucket { puppet:
path => false,
}
You must set catalog_terminus = static_compiler in the puppet masters puppet.conf.
The puppet masters auth.conf must allow authenticated nodes to access the file_bucket_file
endpoint. This is enabled by default (see the path /file rule), but if you have made your
auth.conf more restrictive, you may need to re-enable it.)
If you are using multiple puppet masters, you must congure load balancer anity for agent
nodes. This is because puppet masters other than the one that compiled a given catalog may not
have stored the required le contents in their lebuckets.
store_configs terminus
Part of the storecongs feature. Should not be directly set by end users.
yaml terminus
Store catalogs as at les, serialized using YAML.
certicate
This indirection wraps an OpenSSL::X509::Certificate object, representing a certicate (signed
public key). The indirection key is the certicate CN (generally a hostname).
Indirected Class: Puppet::SSL::Certificate
ca terminus
Manage the CA collection of signed SSL certicates on disk.
disabled_ca terminus
Manage SSL certicates on disk, but reject any remote access to the SSL data store. Used when a
master has an explicitly disabled CA to prevent clients getting confusing success behaviour.
file terminus
Manage SSL certicates on disk.
rest terminus
Find certicates over HTTP via REST.
Puppet 3.6 Reference Manual Indirection Reference 219/325
certicate_request
This indirection wraps an OpenSSL::X509::Request object, representing a certicate signing
request (CSR). The indirection key is the certicate CN (generally a hostname).
Indirected Class: Puppet::SSL::CertificateRequest
ca terminus
Manage the CA collection of certicate requests on disk.
disabled_ca terminus
Manage SSL certicate requests on disk, but reject any remote access to the SSL data store. Used
when a master has an explicitly disabled CA to prevent clients getting confusing success
behaviour.
file terminus
Manage the collection of certicate requests on disk.
memory terminus
Store certicate requests in memory. This is used for testing puppet.
rest terminus
Find and save certicate requests over HTTP via REST.
certicate_revocation_list
This indirection wraps an OpenSSL::X509::CRL object, representing a certicate revocation list
(CRL). The indirection key is the CA name (usually literally ca).
Indirected Class: Puppet::SSL::CertificateRevocationList
ca terminus
Manage the CA collection of certicate requests on disk.
disabled_ca terminus
Manage SSL certicate revocation lists, but reject any remote access to the SSL data store. Used
when a master has an explicitly disabled CA to prevent clients getting confusing success
behaviour.
file terminus
Manage the global certicate revocation list.
Puppet 3.6 Reference Manual Indirection Reference 220/325
rest terminus
Find and save certicate revocation lists over HTTP via REST.
certicate_status
This indirection represents the host that ties a key, certicate, and certicate request together. The
indirection key is the certicate CN (generally a hostname).
Indirected Class: Puppet::SSL::Host
file terminus
Manipulate certicate status on the local lesystem. Only functional on the CA.
rest terminus
Sign, revoke, search for, or clean certicates & certicate requests over HTTP.
data_binding
Where to nd external data bindings.
Indirected Class: Puppet::DataBinding
Terminus Setting: data_binding_terminus
hiera terminus
Retrieve data using Hiera.
none terminus
A Dummy terminus that always returns nil for data lookups.
facts
Indirected Class: Puppet::Node::Facts
Terminus Setting: facts_terminus
active_record terminus
A component of ActiveRecord storecongs and inventory. ActiveRecord-based storecongs and
inventory are deprecated. See http://links.puppetlabs.com/activerecord-deprecation
couch terminus
Store facts in CouchDB. This should not be used with the inventory service; it is for more obscure
custom integrations. If you are wondering whether you should use it, you shouldnt; use PuppetDB
instead.
Puppet 3.6 Reference Manual Indirection Reference 221/325
facter terminus
Retrieve facts from Facter. This provides a somewhat abstract interface between Puppet and Facter.
Its only somewhat abstract because it always returns the local hosts facts, regardless of what you
attempt to nd.
inventory_active_record terminus
Medium-performance fact storage suitable for the inventory service. Most users should use
PuppetDB instead. Note: ActiveRecord-based storecongs and inventory are deprecated. See
http://links.puppetlabs.com/activerecord-deprecation
inventory_service terminus
Find and save facts about nodes using a remote inventory service.
memory terminus
Keep track of facts in memory but nowhere else. This is used for one-time compiles, such as what
the stand-alone puppet does. To use this terminus, you must load it with the data you want it to
contain.
network_device terminus
Retrieve facts from a network device.
rest terminus
Find and save facts about nodes over HTTP via REST.
store_configs terminus
Part of the storecongs feature. Should not be directly set by end users.
yaml terminus
Store client facts as at les, serialized using YAML, or return deserialized facts from disk.
le_bucket_le
Indirected Class: Puppet::FileBucket::File
file terminus
Store les in a directory set based on their checksums.
rest terminus
This is a REST based mechanism to send/retrieve le to/from the lebucket
Puppet 3.6 Reference Manual Indirection Reference 222/325
selector terminus
Select the terminus based on the request
le_content
Indirected Class: Puppet::FileServing::Content
file terminus
Retrieve le contents from disk.
file_server terminus
Retrieve le contents using Puppets leserver.
rest terminus
Retrieve le contents via a REST HTTP interface.
selector terminus
Select the terminus based on the request
le_metadata
Indirected Class: Puppet::FileServing::Metadata
file terminus
Retrieve le metadata directly from the local lesystem.
file_server terminus
Retrieve le metadata using Puppets leserver.
rest terminus
Retrieve le metadata via a REST HTTP interface.
selector terminus
Select the terminus based on the request
instrumentation_data
Indirected Class: Puppet::Util::Instrumentation::Data
local terminus
Undocumented.
Puppet 3.6 Reference Manual Indirection Reference 223/325
rest terminus
Undocumented.
instrumentation_listener
Indirected Class: Puppet::Util::Instrumentation::Listener
local terminus
Undocumented.
rest terminus
Undocumented.
instrumentation_probe
Indirected Class: Puppet::Util::Instrumentation::IndirectionProbe
local terminus
Undocumented.
rest terminus
Undocumented.
key
This indirection wraps an `OpenSSL::PKey::RSA object, representing a private key. The indirection
key is the certicate CN (generally a hostname).
Indirected Class: Puppet::SSL::Key
ca terminus
Manage the CAs private on disk. This terminus only works with the CA key, because thats the only
key that the CA ever interacts with.
disabled_ca terminus
Manage the CA private key, but reject any remote access to the SSL data store. Used when a master
has an explicitly disabled CA to prevent clients getting confusing success behaviour.
file terminus
Manage SSL private and public keys on disk.
Puppet 3.6 Reference Manual Indirection Reference 224/325
memory terminus
Store keys in memory. This is used for testing puppet.
node
Where to nd node information. A node is composed of its name, its facts, and its environment.
Indirected Class: Puppet::Node
Terminus Setting: node_terminus
active_record terminus
A component of ActiveRecord storecongs. ActiveRecord-based storecongs and inventory are
deprecated. See http://links.puppetlabs.com/activerecord-deprecation
exec terminus
Call an external program to get node information. See the External Nodes page for more
information.
ldap terminus
Search in LDAP for node conguration information. See the LDAP Nodes page for more information.
This will rst search for whatever the certicate name is, then (if that name contains a .) for the
short name, then default.
memory terminus
Keep track of nodes in memory but nowhere else. This is used for one-time compiles, such as what
the stand-alone puppet does. To use this terminus, you must load it with the data you want it to
contain; it is only useful for developers and should generally not be chosen by a normal user.
msgpack terminus
Store node information as at les, serialized using MessagePack, or deserialize stored
MessagePack nodes.
plain terminus
Always return an empty node object. Assumes you keep track of nodes in at le manifests. You
should use it when you dont have some other, functional source you want to use, as the compiler
will not work without a valid node terminus.
Note that class is responsible for merging the nodes facts into the node instance before it is
returned.
rest terminus
Puppet 3.6 Reference Manual Indirection Reference 225/325
Get a node via REST. Puppet agent uses this to allow the puppet master to override its environment.
store_configs terminus
Part of the storecongs feature. Should not be directly set by end users.
write_only_yaml terminus
Store node information as at les, serialized using YAML, does not deserialize (write only).
yaml terminus
Store node information as at les, serialized using YAML, or deserialize stored YAML nodes.
report
Indirected Class: Puppet::Transaction::Report
msgpack terminus
Store last report as a at le, serialized using MessagePack.
processor terminus
Puppets report processor. Processes the report with each of the report types listed in the reports
setting.
rest terminus
Get server report over HTTP via REST.
yaml terminus
Store last report as a at le, serialized using YAML.
resource
Indirected Class: Puppet::Resource
active_record terminus
A component of ActiveRecord storecongs. ActiveRecord-based storecongs and inventory are
deprecated. See http://links.puppetlabs.com/activerecord-deprecation
ral terminus
Manipulate resources with the resource abstraction layer. Only used internally.
rest terminus
Maniuplate resources remotely? Undocumented.
Puppet 3.6 Reference Manual Indirection Reference 226/325
store_configs terminus
Part of the storecongs feature. Should not be directly set by end users.
resource_type
Indirected Class: Puppet::Resource::Type
parser terminus
Return the data-form of a resource type.
rest terminus
Retrieve resource types via a REST HTTP interface.
status
Indirected Class: Puppet::Status
local terminus
Get status locally. Only used internally.
rest terminus
Get puppet masters status via REST. Useful because it tests the health of both the web server and
the indirector.
This page autogenerated on 2014-06-12 11:06:47 -0700
Index File: README
(no frames)
Class List Method List File List
Puppet

Puppet, an automated administrative engine for your Linux, Unix, and Windows systems, performs
administrative tasks (such as adding users, installing packages, and updating server congurations)
Puppet 3.6 Reference Manual Puppet 227/325
based on a centralized specication.
Documentation
Documentation for Puppet and related projects can be found online at the Puppet Docs site.
HTTP API
HTTP API Index
Installation
The best way to run Puppet is with Puppet Enterprise, which also includes orchestration features, a
web console, and professional support. The PE documentation is available here.
To install an open source release of Puppet, see the installation guide on the docs site.
If you need to run Puppet from source as a tester or developer, see the running from source guide
on the docs site.
Developing and Contributing
We'd love to get contributions from you! For a quick guide to getting your system setup for
developing take a look at our Quickstart Guide. Once you are up and running, take a look at the
Contribution Documents to see how to get your changes merged in.
For more complete docs on developing with puppet you can take a look at the rest of the developer
documents.
License
See LICENSE le.
Support
Please log tickets and issues at our JIRA tracker. A mailing list is available for asking questions and
getting help from others. In addition there is an active #puppet channel on Freenode.
We use semantic version numbers for our releases, and recommend that users stay as up-to-date
as possible by upgrading to patch releases and minor releases as they become available.
Bugxes and ongoing development will occur in minor releases for the current major version.
Security xes will be backported to a previous major version on a best-eort basis, until the
previous major version is no longer maintained.
For example: If a security vulnerability is discovered in Puppet 4.1.1, we would x it in the 4 series,
most likely as 4.1.2. Maintainers would then make a best eort to backport that x onto the latest
Puppet 3.6 Reference Manual Puppet 228/325
Puppet 3 release.
Long-term support, including security patches and bug xes, is available for commercial
customers. Please see the following page for more details:
Puppet Enterprise Support Lifecycle
Generated on Thu Jun 12 11:08:05 2014 by yard 0.8.7.4 (ruby-2.0.0).
Index File: http_api_index
(no frames)
Class List Method List File List
V1 API Services
Puppet Agents use various network services which the Puppet Master provides in order to manage
systems. Other systems can access these services in order to put the information that the Puppet
Master has to use.
The V1 API is all based o of dispatching to puppet's internal "indirector" framework. Every HTTP
endpoint in V1 follows the form /:environment/:indirection/:key, where * :environment is the
name of the environment that should be in eect for the request. Not all endpoints need an
environment, but the path component must always be specied. * :indirection is the indirection
to dispatch the request to. * :key is the "key" portion of the indirection call.
Using this API requires a signicant amount of understanding of how puppet's internal services are
structured. The following documents provide some specication for what is available and the ways
in which they can be interacted with.
Conguration Management Services
These services are all related to how the Puppet Agent is able to manage the conguration of a
node.
Catalog
File Bucket File
File Content
File Metadata
Report
Informational Services
These services all provide extra information that can be used to understand how the Puppet Master
Puppet 3.6 Reference Manual Puppet 229/325
will be providing conguration management information to Puppet Agents.
Facts
Node
Resource Type
Status
SSL Certicate Related Services
These services are all in support of Puppet's PKI system.
Certicate
Certicate Signing Requests
Certicate Status
Certicate Revocation List
V2 HTTP API
The V2 HTTP API is accessed by prexing requests with /v2.0. Authorization for these endpoints is
still controlled with the auth.conf authorization system in puppet. When specifying the
authorization of the V2 endpoints in auth.conf the /v2.0 prex on V2 API paths must be retained;
the full request path is used.
The V2 API will only accept payloads formatted as JSON and respond with JSON (MIME
application/json).
Endpoints
Environments
Error Responses
All V2 API endpoints will respond to error conditions in a uniform manner and use standard HTTP
response code to signify those errors.
When the client submits a malformed request, the API will return a 400 Bad Request response.
When the client is not authorized, the API will return a 403 Not Authorized response.
When the client attempts to use an HTTP method that is not permissible for the endpoint, the API
will return a 405 Method Not Allowed response.
When the client asks for a response in a format other than JSON, the API will return a 406
Unacceptable response.
When the server encounters an unexpected error during the handling of a request, it will return
a 500 Server Error response.
When the server is unable to nd an endpoint handler for the request that starts with /v2.0, it
will return a 404 Not Found response
Puppet 3.6 Reference Manual Puppet 230/325
The V2 API paths are prexed with /v2.0 instead of /v2 so that it is able to respond with 404, but
not interfere with any environments in the V1 API. v2 is a valid environment name, but v2.0 is not.
All error responses will contain a body, except when it is a HEAD request. The error responses will
uniformly be a JSON object with the following properties:
message: [String] A human readable message explaining the error.
issue_kind: [String] A unique label to identify the error class.
stacktrace (only for 5xx errors): [Array] A stacktrace to where the error occurred.
A JSON schema for the error objects is also available.
Serialization Formats
Puppet sends messages using several dierent serialization formats. Not all REST services support
all of the formats.
PSON
YAML
Generated on Thu Jun 12 11:08:05 2014 by yard 0.8.7.4 (ruby-2.0.0).
Directories: The Main Cong Directory
(Confdir)
Puppets confdir is the traditional /etc/puppet directory, although its actual location varies. It
contains most of Puppets conguration and data.By default, Puppets cong les, manifest
directory, primary module directory, and (sometimes) SSL directory all reside in the confdir.
In short, it is the most important directory in Puppet. All Puppet users must interact with multiple
les and directories in the confdir.
Location
The location of Puppets confdir is somewhat complex. The short version is that its usually at one
of the following locations:
/etc/puppetlabs/puppet
/etc/puppet
C:\ProgramData\PuppetLabs\puppet\etc
The actual default confdir depends on your user account, OS version, and Puppet distribution
Puppet 3.6 Reference Manual Directories: The Main Cong Directory (Confdir) 231/325
(Puppet Enterprise vs. open source). See the table for your operating system below to locate your
actual confdir. For details on system vs. user confdir behavior, see System and User Confdirs
below.
*nix Systems
On Linux and other Unix-like operating systems, Puppet Enterprise and open source Puppet use
dierent system confdirs. The per-user confdir is the same.
Puppet Distribution User Confdir Location
Puppet Enterprise root /etc/puppetlabs/puppet
Open source root /etc/puppet
(Both) non-root ~/.puppet
Windows Systems
On Microsoft Windows, Puppet Enterprise and open source Puppet use the same directories.
However, Windows 2003 uses a dierent system confdir than other supported Windows versions.
(This is because the confdir is based on the COMMON_APPDATA folder, whose location changed to a
simpler value in Windows 7 and 2008.)
Windows Version User Confdir Location
7, 2008, & all
later versions
Administrator %PROGRAMDATA%\PuppetLabs\puppet\etc (defaults to C:\ProgramData\PuppetLabs\puppet\etc)
2003 Administrator %ALLUSERSPROFILE%\Application Data\PuppetLabs\puppet\etc (defaults to C:\Documents and
Settings\All Users\Application Data\PuppetLabs\puppet\etc)
(All) non-
Administrator
%UserProfile%\.puppet (defaults to C:\Users\USER_NAME\.puppet on 7+ and 2008+)
System and User Confdirs
Depending on the run environment, Puppet will use either a system-wide confdir or a per-user
confdir:
When Puppet is running as a non-root user, it defaults to a confdir in that users home directory.
The system confdir is used when Puppet is running as root or Administrator, either directly or via
sudo. (Puppet agent generally runs as root or Administrator when managing a system.)
The system confdir is also used when Puppet is started as root before switching users and
Note: Puppets confdir can be specied on the command line with the --confdir option, but
it cant be set via puppet.conf. (This is because it needs the confdir to even nd the cong
le.) If --confdir isnt specied when a Puppet application is started, it will always use the
default confdir location.
Puppet 3.6 Reference Manual Directories: The Main Cong Directory (Confdir) 232/325
dropping privileges, which is what a WEBrick puppet master does. Note that when puppet
master is running as a Rack application, the config.ru le must explicitly set --confdir to
the system confdir. The example config.ru le provided with the Puppet source does this.
The system confdir is the most common, since Puppet generally runs as a service with administrator
privileges and the admin commands (like puppet cert) must be run with sudo.
Interpolation of $confdir
Since the value of the confdir is discovered before other settings, you can safely reference it (with
the $confdir variable) in the value of any other setting in puppet.conf or on the command line:
[master]
modulepath =
$confdir/patched_modules:$confdir/modules:/usr/share/puppet/modules
If you need to set nonstandard values for some settings, this allows you to avoid absolute paths and
keep your Puppet-related les together.
Contents
Puppets confdir contains several cong les and several directories of data and Puppet code. Their
locations can be changed with settings, but most users should use the default layout.
Since the contents of the confdir are Puppets most important les, each one has its own page of
documentation.
Items labeled master only below may also be present on standalone puppet apply nodes, since
they act as both masters and agents.
Code and Data Directories
modules the main directory for Puppets modules. (Master only.)
manifests contains the main starting point for catalog compilation. (Master only.)
environments contains alternate versions of the modules and manifests directories, to allow
code changes to be tested on smaller sets of nodes before entering production. (Master only.)
ssl contains each nodes certicate infrastructure. (All nodes.)
Cong Files
puppet.conf Puppets main cong le. (All nodes.)
auth.conf access control rules for the puppet masters network services. (Master only, unless
listen is enabled.)
autosign.conf a list of pre-approved certicate requests. (CA master only.)
Puppet 3.6 Reference Manual Directories: The Main Cong Directory (Confdir) 233/325
csr_attributes.yaml optional data to be inserted into new certicate requests. (All nodes.)
device.conf conguration for network devices managed by the puppet device command.
(All nodes.)
fileserver.conf conguration for additional leserver mount points. (Master only.)
hiera.yaml conguration for the Hiera data lookup system. (Master only.)
routes.yaml advanced conguration of indirector behavior. (Master only.)
tagmail.conf instructions for mailing important Puppet events to administrators. (Master
only.)
Directories: The Main Manifest(s)
Puppet always starts compiling with either a single manifest le or a directory of manifests that get
treated like a single le. This main starting point is called the main manifest or site manifest.
For more information on how the site manifest is used in catalog compilation, see the reference
page on catalog compilation.
Location
With Puppet Master
When using no environments, the main manifest will default to $confdir/manifests/site.pp,
which is a single le. (See here for info about the confdir.) This location can be congured with
the manifest setting.
If you are using directory environments, the main manifest will always be
$confdir/environments/<ENVIRONMENT NAME>/manifests, which is a directory. The location of
the environments directory can be congured with the environmentpath setting; see the page
about directory environments for more details.
If you are using cong le environments, Puppet will look for a manifest setting in that
environments cong section; if it isnt set there, Puppet will fall back to the manifest setting in
the [master] or [main] section. See the page about cong le environmentsfor more details.
The main manifest may be a single le or a directory of .pp les. To check the actual manifest your
puppet master will use, run puppet config print manifest --section master --environment
<ENVIRONMENT>.
Recommended: If youre using the main manifest heavily instead of relying on an ENC,
consider changing the manifest setting to $confdir/manifests. This lets you split up your
top-level code into multiple les while avoiding the import keyword. It will also match the
Puppet 3.6 Reference Manual Directories: The Main Manifest(s) 234/325
With Puppet Apply
The puppet apply command requires a manifest as an argument on the command line. (For
example: puppet apply /etc/puppetlabs/puppet/manifests/site.pp.) It may be a single le or a
directory of les.
Puppet apply does not use the manifest setting or environment-specic manifests; it always uses
the manifest given on the CLI.
Directory Behavior (vs. Single File)
If the main manifest is a directory, Puppet will parse every .pp le in the directory in alphabetical
order and then evaluate the combined manifest.
Puppet will act as though the whole directory were just one big manifest; for example, a variable
assigned in the le 01_all_nodes.pp would be accessible in node_web01.pp.
Puppet will only read the rst level of lesin a manifest directory; it wont descend into
subdirectories.
Directories: The Modulepath (Default Cong)
The puppet master service and the puppet apply command both load most of their content from
modules. (See the page on module structure and behavior for more details.)
Puppet automatically loads modules from one or more directories. The list of directories Puppet will
nd modules in is called the modulepath.
Format
/etc/puppet/modules:/usr/share/puppet/modules
The modulepath is a list of directories separated by the system path-separator character. On *nix
systems this is the colon ( :, as seen above), and on Windows it is the semi-colon ( ;).
It is an ordered list, with earlier directories having priority over later ones. See Loading Content
from Modules below.
Contents
Every directory in the modulepath should only contain valid Puppet modules.
For details about module contents and structure, see the documentation on modules.
behavior of simple environments.
Puppet 3.6 Reference Manual Directories: The Modulepath (Default Cong) 235/325
Location
By default, the modulepath will usually be something like:
<ACTIVE ENVIRONMENT'S MODULES DIRECTORY>:$confdir/modules:<SYSTEM MODULES DIRECTORY>
The location of the modulepath is congured dierently, depending on whether directory
environments are enabled:
Conguration Location of modulepath
Cong le environmentsor no environments Value of modulepath setting (defaults to the base modulepath)
Directory environments Active environments modules directory, followed by the base modulepath.
You can view the eective modulepath for any environment by specifying the environment when
requesting the setting value:
$ sudo puppet config print modulepath --section master --environment test
/etc/puppet/environments/test/modules:/etc/puppet/modules:/usr/share/puppet/modules
The Base Modulepath
The base modulepath is a list of global module directories for use with all directory environments. It
also serves as the default value for the modulepath setting, which is used when directory
environments are disabled. It can be congured with the basemodulepath setting, but its default
value is probably suitable for you unless youre doing something unusual.
The default value of the basemodulepath setting depends on your OS and the distribution of
Puppet in use. This table lists the default basemodulepath values.
Note that all default values include $confdir/modules; see here for info about the confdir.
OS and Distro Default Base Modulepath
*nix (Puppet Enterprise) $confdir/modules:/opt/puppet/share/puppet/modules
*nix (open source) $confdir/modules:/usr/share/puppet/modules
Windows (PE and FOSS) $confdir\modules
Examples of Default Modulepaths
Puppet Enterprise, no environments, default settings:
/etc/puppetlabs/puppet/modules:/opt/puppet/share/puppet/modules
Puppet 3.6 Reference Manual Directories: The Modulepath (Default Cong) 236/325
Open source Puppet, directory environments enabled with environmentpath =
$confdir/environments, active environment is dev:
/etc/puppet/environments/dev/modules:/etc/puppet/modules:/usr/share/puppet/modules
Conguring the Modulepath
If you are not using environments, you can directly congure the modulepath with the
modulepath setting. This should generally be set in the [main] section of puppet.conf, so it can
be used by all commands and services.
If you are using directory environments, the rst element of the modulepath will always be the
active environments modules directory. However, you can congure global module directories
with the basemodulepath setting (see above). This should generally be set in the [main] section
of puppet.conf.
If you are using environment cong sections, you can set modulepath in each environments
section of puppet.conf. If that setting is absent in a given environment, Puppet will fall back to
the global value of the modulepath setting.
If you are using dynamic environments, you can set the modulepath setting in [main] and use
the $environment variable in some of the directory names.
Loading Content from Modules
Puppet will use modules from every directory in the modulepath.
Empty and Absent Directories
Directories in the modulepath may be empty, and may even be absent. In both cases, this is not an
error; it just means no modules will be loaded from that directory.
If no modules are present across the entire modulepath, or if modules are present but none of
them contains a lib directory, then puppet agent will log an error when attempting to sync plugins
from the puppet master. This error is benign and will not prevent the rest of the puppet run.
Duplicate or Conicting Modules and Content
If the modulepath contains multiple modules with the same name, Puppet will use the version from
the directory that comes earliest in the modulepath. This allows directories earlier in the
modulepath to override the later directories.
For most content, this earliest-module-wins behavior is on an all-or-nothing, per-module basis
all of the manifests, les, and templates in the winning version will be available for use, and *none
of that content from any subsequent versions will be available. This behavior covers:
Puppet code (from manifests)
Files (from files)
Puppet 3.6 Reference Manual Directories: The Modulepath (Default Cong) 237/325
Templates (from templates)
External facts (from facts.d)
Ruby plugins synced to agent nodes (from lib)
Directories: The SSLdir
Puppet stores its certicate infrastructure in the ssldir. This directory is used with a similar layout
on all Puppet nodes, whether they are acting as agent nodes, puppet master servers, or the CA
puppet master.
Location
By default, the ssldir is located at $confdir/ssl. (See here for info about the confdir.)
Its location can be congured with the ssldir setting. To check the actual ssldir on one of your
nodes, run puppet config print ssldir.
However, Puppet occasionally shows problematic behavior with Ruby plugins loaded directly
from modules. This includes:
Plugins used by the puppet master (custom resource types, custom functions)
Plugins used by puppet apply
Plugins that happen to be present in puppet agents modulepath (which should generally
be empty, but may not be when running puppet agent on a node that is also a puppet
master server)
With these plugins, the earlier module still wins, but the plugins are handled on a per-le
basis instead of per-module. This means that if a duplicate module in a later directory has
additional plugin les that dont exist in the winning module, those extra les will be loaded,
and Puppet will use a mixture of les from the winning and duplicate modules.
The upshot is, if you do a major refactor of the Ruby plugins in some module and then
maintain two versions of that module in your modulepath, it can sometimes result in
weirdness.
This is essentially the same Ruby loading problem that environments have, as described
elsewhere in this manual. Its not intentional, but its not likely to get xed soon, since its a
byproduct of the way Ruby works and Puppet only has a limited amount of control over it.
Note: Many open-source Puppet packages for Linux put the ssldir in the vardir instead of the
confdir. (The right place for it under the FHS is debatable; the contents are automatically
Puppet 3.6 Reference Manual Directories: The SSLdir 238/325
Summary of Contents
The ssldir contains Puppets certicates, private keys, certicate signing requests (CSRs), and other
cryptographic documents.
Agent nodes and puppet masters require a private key ( private_keys/<certname>.pem), a public
key ( public_keys/<certname.pem>), a signed certicate (certs/<certname>.pem), a copy of the CA
certicate (certs/ca.pem), and a copy of the certicate revocation list (CRL) (crl.pem). They usually
also retain a copy of their CSR after submitting it ( certificate_requests/<certname>.pem). If
these les dont exist, they are either generated locally or requested from the CA puppet master.
Since agent and master credentials are identied by certname, a puppet agent process and puppet
master process running on the same server may use the same credentials.
The Puppet CA, which runs on the CA puppet master server, requires similar credentials
(private/public key, certicate, master copy of the CRL). It also maintains a list of all signed
certicates in the deployment, a copy of each signed certicate, and an incrementing serial number
for new certicates. All of the CAs data is stored in the ca subdirectory, to keep it separated from
any normal Puppet credentials on the same server.
All of the les and directories in the ssldir have corresponding Puppet settings, which can be used
to individually change their locations. However, this is generally not recommended.
Detailed Contents
The permissions mode of the ssldir should be 0771, and it and every le it contains should be
owned by the user Puppet runs as (i.e., root or Administrator on puppet agent nodes and
defaulting to puppet or pe-puppet on a puppet master server). Ownership and permissions in the
ssldir are generally managed automatically.
The layout of the ssldir is as follows:
ca (directory) Contains all les used by Puppets built-in certicate authority (CA). This
directory must only exist on the CA puppet master server. Mode: 0755. Setting: cadir.
ca_crl.pem The master copy of the certicate revocation list (CRL) managed by the CA.
Mode: 0644. Setting: cacrl.
generated and will tend to grow, but are also important, relatively dicult to replace, and
can be considered conguration.)
If a distro changes the ssldir location, it will do so by setting ssldir in the
$confdir/puppet.conf le, usually in the [main] section. You can nd out for sure by
printing the ssldir setting value.
Puppet 3.6 Reference Manual Directories: The SSLdir 239/325
ca_crt.pem The CAs self-signed certicate. This cannot be used as a puppet master or
puppet agent certicate; it can only be used to sign certicates. Mode: 0644. Setting: cacert.
ca_key.pem The CAs private key. Tied for most security-critical le in the entire Puppet
certicate infrastructure. Mode: 0640. Setting: cakey.
ca_pub.pem The CAs public key. Mode: 0644. Setting: capub.
inventory.txt A list of all certicates the CA has signed, along with their serial numbers
and validity periods. Mode: 0644. Setting: cert_inventory.
private (directory) Contains only one le. Mode: 0750. Setting: caprivatedir.
ca.pass The (randomly generated) password to the CAs private key. Tied for most
security-critical le in the entire Puppet certicate infrastructure. Mode: 0640. Setting:
capass.
requests (directory) Contains certicate signing requests (CSRs) that were received but
have not yet been signed. The CA deletes CSRs from this directory after signing them. Mode:
0755. Setting: csrdir.
<name>.pem Individual CSR les.
serial A le containing the serial number for the next certicate the CA will sign. This is
incremented with each new certicate signed. Mode: 0644. Setting: serial.
signed (directory) Contains copies of all certicates the CA has signed. Mode: 0755.
Setting: signeddir.
<name>.pem Individual signed certicate les.
certificate_requests (directory) Contains any CSRs generated by this node in preparation
for submission to the CA. CSRs persist in this directory even after they have been submitted and
signed. Mode: 0755. Setting: requestdir.
<certname>.pem This nodes CSR. Mode: 0644. Setting: hostcsr.
certs (directory) Contains any signed certicates present on this node. This includes the
nodes own certicate, as well as a copy of the CA certicate (for use when validating certicates
presented by other nodes). Mode: 0755. Setting: certdir.
<certname>.pem This nodes certicate. Mode: 0644. Setting: hostcert.
ca.pem A local copy of the CA certicate. Mode: 0644. Setting: localcacert.
crl.pem A copy of the certicate revocation list (CRL) retrieved from the CA, for use by puppet
agent or puppet master. Mode: 0644. Setting: hostcrl.
private (directory) Usually does not contain any les. Mode: 0750. Setting: privatedir.
password The password to a nodes private key. Usually not present. The conditions in
which this le would exist are not dened. Mode: 0640. Setting: passfile.
Puppet 3.6 Reference Manual Directories: The SSLdir 240/325
private_keys (directory) Contains any private keys present on this node. This should
generally only include the nodes own private key, although on the CA it may also contain any
private keys created by the puppet cert generate command. It will never contain the private
key for the CA certicate. Mode: 0750. Setting: privatekeydir.
<certname>.pem This nodes private key. Mode: 0600. Setting: hostprivkey.
public_keys (directory) Contains any public keys generated by this node in preparation for
generating a CSR. Mode: 0755. Setting: publickeydir.
<certname>.pem This nodes public key. Mode: 0644. Setting: hostpubkey.
Directories: The Vardir
Puppets vardir is the traditional /var/lib/puppet directory, although its actual location varies. It
contains dynamic and/or growing data that Puppet creates automatically in the course of its normal
operations. Some of this data can be mined for interesting analysis, or to integrate other tools with
Puppet; other parts are just infrastructure and should be ignored by most or all users.
Location
The location of Puppets vardir is somewhat complex. The short version is that its usually at one of
the following locations:
/var/opt/lib/pe-puppet
/var/lib/puppet
C:\ProgramData\PuppetLabs\puppet\var
The actual default vardir depends on your user account, OS version, and Puppet distribution
(Puppet Enterprise vs. open source). See the table for your operating system below. For details on
system vs. user vardir behavior, see System and User Vardirs below.
*nix Systems
On Linux and other Unix-like operating systems, Puppet Enterprise and open source Puppet use
dierent system vardirs. The per-user vardir is the same, and is located inside the per-user confdir.
Puppet Distribution User Vardir Location
Note: Puppets vardir can be specied on the command line with the --vardir option, but it
cant be set via puppet.conf. If --vardir isnt specied when a Puppet application is started,
it will always use the default vardir location.
Puppet 3.6 Reference Manual Directories: The Vardir 241/325
Puppet Enterprise root /var/opt/lib/pe-puppet
Open source root /var/lib/puppet
(Both) non-root ~/.puppet/var
Windows Systems
On Microsoft Windows, Puppet Enterprise and open source Puppet use the same directories.
However, Windows 2003 uses a dierent system vardir than other supported Windows versions.
(This is because the vardir is based on the COMMON_APPDATA folder, whose location changed to a
simpler value in Windows 7 and 2008.)
The per-user vardir is the same, and is located inside the per-user confdir.
Windows Version User Vardir Location
7, 2008, & all
later versions
Administrator %PROGRAMDATA%\PuppetLabs\puppet\var (defaults to C:\ProgramData\PuppetLabs\puppet\var)
2003 Administrator %ALLUSERSPROFILE%\Application Data\PuppetLabs\puppet\var (defaults to C:\Documents and
Settings\All Users\Application Data\PuppetLabs\puppet\var)
(all) non-
Administrator
%UserProfile%\.puppet\var (defaults to C:\Users\USER_NAME\.puppet\var on 7+ and 2008+)
System and User Vardirs
Depending on the run environment, Puppet will use either a system-wide vardir or a per-user
vardir:
When Puppet is running as a non-root user, it defaults to a vardir in that users home directory.
The system vardir is used when Puppet is running as root or Administrator, either directly or via
sudo. (Puppet agent generally runs as root or Administrator when managing a system.)
The system vardir is also used when Puppet is started as root before switching users and
dropping privileges, which is what a WEBrick puppet master does. Note that when puppet
master is running as a Rack application, the config.ru le must explicitly set --vardir to the
system vardir. The example config.ru le provided with the Puppet source does this.
The system vardir is the most common, since Puppet generally runs as a service with administrator
privileges and the admin commands (like puppet cert) must be run with sudo.
Interpolation of $vardir
Since the value of the vardir is discovered before other settings, you can safely reference it (with the
$vardir variable) in the value of any other setting in puppet.conf or on the command line:
[main]
ssldir = $vardir/ssl
Puppet 3.6 Reference Manual Directories: The Vardir 242/325
If you need to set nonstandard values for some settings, this allows you to avoid absolute paths and
keep your Puppet-related les together.
Contents
The vardir contains several directories. Most of these subdirectories contain a variable amount of
automatically generated data; some of them contain notable individual les. Some directories are
used only by agent or master processes.
The default layout of the vardir is as follows. Most of the les and directories can have their
locations changed with settings in puppet.conf. The link for each item goes to its description in the
conguration reference.
bucket ( bucketdir)
client_data ( client_datadir)
clientbucket ( clientbucketdir)
client_yaml ( clientyamldir)
devices ( devicedir)
lib/facter ( factpath)
facts ( factpath)
facts.d ( pluginfactdest)
lib ( libdir) (also plugindest) Puppet uses this as a cache for plugins (custom facts, types
and providers, functions) synced from a puppet master. It shouldnt be directly modied by the
user. It can be safely deleted, and the plugins will be restored on the next Puppet run.
puppet-module ( module_working_dir)
skeleton ( module_skeleton_dir)
log ( logdir)
http.log ( httplog)
masterhttp.log ( masterhttplog)
puppetmaster.log ( masterlog)
puppetd.log ( puppetdlog)
reports ( reportdir) When the store report is enabled, a puppet master will store all reports
received from agents as YAML les in this directory. These can be easily mined for analysis by an
out-of-band process.
rrd ( rrddir)
run ( rundir)
Puppet 3.6 Reference Manual Directories: The Vardir 243/325
${run_mode}.pid ( pidfile)
server_data ( serverdatadir)
state ( statedir)
agent_catalog_run.lock ( agent_catalog_run_lockfile)
agent_disabled.lock ( agent_disabled_lockfile)
classes.txt ( classfile) This le is a favorite for external integration. It lists all of the
classes assigned to this agent node.
graphs ( graphdir) Agent nodes write a set of .dot graph les to this directory when
graphing is enabled. These graphs can be used to diagnose problems with catalog
application, as well as to visualize the conguration catalog.
last_run_summary.yaml ( lastrunfile)
last_run_report.yaml ( lastrunreport)
localconfig ( localconfig)
resources.txt ( resourcefile)
state.yaml ( statefile)
templates ( templatedir) This directory generally shouldnt be used; templates should be
stored in modules.
yaml ( yamldir)
Directory Environments
Environments are isolated groups of puppet agent nodes. A puppet master server can serve each
environment with completely dierent main manifests and modulepaths.
This frees you to use dierent versions of the same modules for dierent populations of nodes,
which is useful for testing changes to your Puppet code before implementing them on production
machines. (You could also do this by running a separate puppet master for testing, but using
environments is often easier.)
Directory Environments vs. Cong File Environments
There are two ways to set up environments on a puppet master: directory environments, and
cong le environments.Note that these are mutually exclusive enabling one will
completely disable the other.
This page is about directory environments, which are easier to use and will eventually
Puppet 3.6 Reference Manual Directory Environments 244/325
Things to Know About Directory Environments
They Disable Cong File Environments
If directory environments are enabled, they will completely disable cong le environments. This
means:
Puppet will always ignore the manifest, modulepath, and config_version settings in
puppet.conf.
Puppet will always ignore any environment cong sectionsin puppet.conf.
Instead, the eective site manifest and modulepath will always come from the active environment.
Uncongured Environments Arent Allowed
If a node is assigned to an environment which doesnt exist that is, there is no directory of that
name in any of the environmentpath directories the puppet master will fail compilation of its
catalog.
Enabling Directory Environments
Directory environments are disabled by default. To enable them, you must:
Set environmentpath = $confdir/environments in the puppet masters puppet.conf (in the
[master] or [main] section).
You can also set other values for environmentpath. See the About environmentpath section
below for more details.
Create at least one directory environment. See the Setting Up Environments on a Puppet Master
section below for details.
You must have a directory environment for every environment that any nodes are assigned to.
At minimum, you must have a production environment. (You can make one quickly by
moving your $confdir/manifests directory to
$confdir/environments/production/manifests.)
Optionally, set the basemodulepath setting for global modules that should be available in all
environments.
Most people are ne with the default value. See the About basemodulepath section below
for more details.
Once you do this, directory environments will be enabled and cong le environments will be
disabled.
replace cong le environments completely.
Puppet 3.6 Reference Manual Directory Environments 245/325
About environmentpath
The puppet master will only look for environments in certain directories, listed by the
environmentpath setting in puppet.conf. The recommended value for environmentpath is
$confdir/environments. (See here for info on the confdir.)
If you need to manage environments in multiple directories, you can set environmentpath to a
colon-separated list of directories. (For example:
$confdir/temporary_environments:$confdir/environments.) Puppet will search these directories
in order, with earlier directories having precedence.
About basemodulepath
Although environments should contain their own modules, you might want some modules to be
available to all environments.
The basemodulepath setting congures the global module directories. By default, it includes
$confdir/modules, which is good enough for most users. The default may also include another
directory for system modules, depending on your OS and Puppet distribution:
OS and Distro Default basemodulepath
*nix (Puppet Enterprise) $confdir/modules:/opt/puppet/share/puppet/modules
*nix (open source) $confdir/modules:/usr/share/puppet/modules
Windows (PE and foss) $confdir\modules
To add additional directories containing global modules, you can set your own value for
basemodulepath. See the page on the modulepath for more details about how Puppet loads
modules from the modulepath.
Setting Up Environments on a Puppet Master
A directory environment is just a directory that follows a few conventions:
The directory name is the environment name.
It should contain a modules directory and a manifests directory. (These are allowed to be empty
or absent; see sections below for details.)
It may contain an environment.conf le, which can locally override several settings.
It must be located in a directory where the puppet master searches for environments. (The
recommended directory is $confdir/environments. See About environmentpath above.)
Once those conditions are met, the environment is fully congured. When serving nodes assigned
to that environment, the puppet master will use the modules and the main manifest from that
environment.
Puppet 3.6 Reference Manual Directory Environments 246/325
Manifests Directory Main Manifest
An environments manifests directory will be used as the main manifest when compiling catalogs
for nodes in that environment. This uses the directory-as-manifest behavior.
If the manifests directory is empty or absent, Puppet will not fall back to the default main manifest;
instead, it will behave as though you used a totally blank main manifest.
You can use a dierent main manifest by setting manifest in environment.conf. (See below.) The
global manifest setting from puppet.conf wont be used.
Modules Directory First Directory in Modulepath
When serving nodes from a directory environment, the eective modulepath will be:
<MODULES DIRECTORY FROM ENVIRONMENT>:$basemodulepath
That is, Puppet will add the environments modules directory to the value of the basemodulepath
setting, with the environment getting priority.
If the modules directory is empty or absent, Puppet will only use modules from directories in the
basemodulepath.
You can congure a dierent modulepath for the environment by setting modulepath in
environment.conf. (See below.) The global modulepath setting from puppet.conf wont be used.
Puppet 3.6 Reference Manual Directory Environments 247/325
For details on how Puppet loads modules from modulepath directories, see the reference page
about the modulepath.
The environment.conf File
An environment can contain an environment.conf le, which can override values for the following
settings:
modulepath
manifest
config_version
environment_timeout
See the page on environment.conf for more details.
Allowed Names
Environment names can contain letters, numbers, and underscores. That is, they must match the
following regular expression:
\A[a-z0-9_]+\Z
Additionally, there are four forbidden environment names:
main
master
agent
user
These names cant be used because they conict with the primary cong sections. This can be a
problem with Git, because its default branch is named master. You may need to rename the master
branch to something like production or stable (e.g. git branch -m master production).
CHECKING THE MODULEPATH
You can view an environments eective modulepath by specifying the environment when
requesting the setting value:
$ sudo puppet config print modulepath --section master --environment test
/etc/puppet/environments/test/modules:/etc/puppet/modules:/usr/share/puppet/modules
Puppet 3.6 Reference Manual Directory Environments 248/325
Assigning Nodes to Environments
By default, all nodes are assigned to a default environment named production.
There are two ways to assign nodes to a dierent environment:
Via your ENC or node terminus
Via each agent nodes puppet.conf
The value from the ENC is authoritative, if it exists. If the ENC doesnt specify an environment, the
nodes cong value is used.
Note that nodes cant be assigned to uncongured environments. If a node is assigned to an
environment which doesnt exist that is, there is no directory of that name in any of the
environmentpath directories the puppet master will fail compilation of its catalog.
Via an ENC
The interface to set the environment for a node will be dierent for each ENC. Some ENCs cannot
manage environments.
When writing an ENC, simply ensure that the environment: key is set in the YAML output that the
ENC returns. See the documentation on writing ENCs for details.
If the environment key isnt set in the ENCs YAML output, the puppet master will just use the
environment requested by the agent.
Via the Agents Cong File
In puppet.conf on each agent node, you can set the environment setting in either the agent or
main cong section. When that node requests a catalog from the puppet master, it will request that
environment.
If you are using an ENC and it species an environment for that node, it will override whatever is in
the cong le.
Referencing the Environment in Manifests
In Puppet manifests, you can get the name of the current environment by using the $environment
variable, which is set by the puppet master.
Tuning Environment Caching
The puppet master loads environments on request, and it caches data associated with them to give
faster service to other nodes in that environment. Cached environments will time out and be
discarded after a while, after which theyll be loaded on request again.
Puppet 3.6 Reference Manual Directory Environments 249/325
You can congure environment cache timeouts with the environment_timeout setting. This can be
set globally in puppet.conf, and can also be overridden per-environment in environment.conf. See
the description of the environment_timeout setting for details on allowed values. The default
cache timeout is ve seconds, which doesnt give much of a performance boost but also wont
surprise you by ignoring their le changes.
To get more performance from your puppet master, you may want to tune the timeout for your
most heavily used environments. Getting the most benet involves a tradeo between speed,
memory usage, and responsiveness to changed les. The general best practice is:
Long-lived, slowly changing, relatively homogenous, highly populated environments (like
production) will give the most benet from longer timeouts. You might be able to set this to
hours, or unlimited if youre content to let cache stick around until your Rack server kills a given
puppet master process.
Rapidly changing dev environments should have short timeouts: a few seconds, or 0 if you dont
want to wait.
Sparsely populated environments should have short-ish timeouts, which are just long enough to
help out if a cluster of nodes all hit the master at once, but wont clog your RAM with a bunch of
rarely used data. Five to ten seconds is ne.
Extremely heterogeneous environments where you have a lot of modules and each node uses
a dierent tiny subset will sometimes perform worse with a long timeout. (This can cause
excessive memory usage and garbage collection without giving back any performance boost.)
Leave these with short timeouts of 5-10 seconds.
Other Information About Environments
This section of the Puppet reference manual has several other pages about environments:
Suggestions for Use common patterns and best practices for using environments.
Limitations of Environments environments mostly work, but they can be a bit wobbly in several
situations.
Environments and Puppets HTTPS Interface this page explains how environment information
is embedded in Puppets HTTPS requests, and how you can query environment data in order to
build Puppet extensions.
Cong-le Environments
Cong File Environments Are Deprecated
If your puppet.conf le:
Contains any environment cong blocks
Puppet 3.6 Reference Manual Cong-le Environments 250/325
Environments are isolated groups of puppet agent nodes. A puppet master server can serve each
environment with completely dierent main manifests and modulepaths.
This frees you to use dierent versions of the same modules for dierent populations of nodes,
which is useful for testing changes to your Puppet code before implementing them on production
machines. (You could also do this by running a separate puppet master for testing, but using
environments is often easier.)
Setting Up Environments on a Puppet Master
Puppets cong le provides two ways to congure environments: per-environment cong sections,
and interpolation of the $environment variable in settings values (AKA dynamic environments).
Environment Cong Sections
The puppet.conf lehas four primary cong sections. The puppet master application will usually
use settings from the master section, and will fall back to the main section for settings that arent
dened in master.
You can also make additional cong sections for environments. If available, Puppet will use settings
from an environment cong section when serving nodes assigned to that environment. If an
environment-specic section doesnt exist or doesnt set values for some settings, Puppet will fall
back to the master and then main sections as normal.
Sets global values for the manifest, modulepath, or config_version settings
then the puppet master will log deprecation warnings. (Interpolating the $environment
variable wont log warnings, since its benign without the global settings and is useful in
environment.conf les.)
In a future version of Puppet (probably Puppet 4), directory environments will always be
enabled, and the default production environment will take the place of the global
manifest/modulepath/config_version settings.
When you have time, you should read up on directory environments and start using them.
Directory Environments vs. Cong File Environments
There are two ways to set up environments on a puppet master: directory environments, and
cong le environments.
This page is about cong le environments, which are deprecated and are more complex to
use. You should consider moving to directory environments soon.
Puppet 3.6 Reference Manual Cong-le Environments 251/325
[main]
server = puppet.example.com
certname = puppetmaster1.example.com
trusted_node_data = true
[master]
dns_alt_names =
puppetmaster1.example.com,puppetmaster1,puppet.example.com,puppet
autosign = false
[test]
modulepath =
$confdir/environments/test/modules:$condfir/modules:/usr/share/puppet/modules
manifest = $confdir/environments/test/manifests
config_version = /usr/bin/git --git-dir $confdir/environments/test/.git rev-
parse HEAD
In this example, the test environment has its own separate values for the modulepath, manifest,
and config_version settings, and Puppet will use those when serving nodes in that environment.
When serving nodes in other environments, the puppet master will use the global values for those
settings, which in this example are left to their defaults.
USABLE SETTINGS
Only certain settings can be used in an environment cong section. Although Puppet will allow you
to set any settings there, it will only actually read and use a few of them. Those usable settings are:
modulepath
manifest
config_version
The templatedir setting will also work, but we recommend against using the old-style global
template directory.
Dynamic Environments
Alternately, you can use the global values for the modulepath and manifest settings (via the
master or main section), but set their values to use the special $environment variable. (Note that if
an environment cong section exists for the active environment, it will get priority.)
When getting values for settings, Puppet will replace $environment with the name of the active
environment. This allows you to mimic directory environments:
[master]
manifest = $confdir/environments/$environment/manifests
modulepath = $confdir/environments/$environment/modules
In this example, you could create a directory for each environment in the $confdir/environments
Puppet 3.6 Reference Manual Cong-le Environments 252/325
directory.
When using dynamic environments, theres not a very good way to set config_version. Possibly
due to the timing of how settings are loaded, interpolation of $environment in that setting doesnt
seem to work. In a future version of Puppet, directory environments will provide a cleaner way to do
this.
Similarly, you shouldnt interpolate $environment into any other settings besides manifest and
modulepath; the results are likely to be unpredictable.
Allowed Names
Environment names can contain letters, numbers, and underscores. That is, they must match the
following regular expression:
\A[a-z0-9_]+\Z
Additionally, there are four forbidden environment names:
main
master
agent
user
These names cant be used because they conict with the primary cong sections. This can be a
problem with Git, because its default branch is named master. You may need to rename the master
branch to something like production or stable (e.g. git branch -m master production).
No Interaction with Directory Environments
If directory environments are enabled (by setting the environmentpath setting; see Enabling
Directory Environments), any cong le environments will be completely ignored.
If youve accidentally congured the same environment in multiple ways (see the page on directory
environments), the precedence goes like this:
Cong sections directory environments dynamic ($environment) environments
If an environment cong section exists for the active environment, Puppet will ignore the directory
environment it would have otherwise used. This means it will use the standard manifest and
modulepath settings to serve nodes in that environment. If values for those settings are specied in
the environment cong section, those will be used; otherwise, Puppet will use the global values.
If the global values for the manifest and modulepath settings use the $environment variable, they
will only be used when a directory environment doesnt exist for the active environment.
Puppet 3.6 Reference Manual Cong-le Environments 253/325
Similarly, if the global manifest or modulepath use $environment, any cong section environments
will override them.
Uncongured Environments Global Settings
If a node is assigned to an environment for which a cong section doesnt exist, or if the cong
section does not specify a value for one or more settings, the puppet master will use the global
manifest and modulepath settings to serve that node.
If the values of the manifest or modulepath settings point to any les or directories that dont exist
(due to interpolating $environment for an unexpected environment name), Puppet will act as
though those directories were empty.
Assigning Nodes to Environments
By default, all nodes are assigned to a default environment named production.
There are two ways to assign nodes to a dierent environment:
Via your ENC or node terminus
Via each agent nodes puppet.conf
The value from the ENC is authoritative, if it exists. If the ENC doesnt specify an environment, the
nodes cong value is used.
With cong le environments, nodes can be assigned to environments that are not congured. This
will cause them to fall back to global values for modulepath and manifest.
Via an ENC
The interface to set the environment for a node will be dierent for each ENC. Some ENCs cannot
manage environments.
When writing an ENC, simply ensure that the environment: key is set in the YAML output that the
ENC returns. See the documentation on writing ENCs for details.
If the environment key isnt set in the ENCs YAML output, the puppet master will just use the
environment requested by the agent.
Via the Agents Cong File
In puppet.conf on each agent node, you can set the environment setting in either the agent or
main cong section. When that node requests a catalog from the puppet master, it will request that
environment.
If you are using an ENC and it species an environment for that node, it will override whatever is in
the cong le.
Puppet 3.6 Reference Manual Cong-le Environments 254/325
Referencing the Environment in Manifests
In Puppet manifests, you can get the name of the current environment by using the $environment
variable, which is set by the puppet master.
Tuning Environment Caching
With cong le environments, theres very little performance to be gained by tuning the
environment_timeout setting. It can be ignored until youre ready to switch to directory
environments.
Other Information About Environments
This section of the Puppet reference manual has several other pages about environments:
Suggestions for Use common patterns and best practices for using environments.
Limitations of Environments environments mostly work, but they can be a bit wobbly in several
situations.
Environments and Puppets HTTPS Interface this page explains how environment information
is embedded in Puppets HTTPS requests, and how you can query environment data in order to
build Puppet extensions.
Environments: Suggestions for Use
The main uses for environments tend to fall into a few categories. A single group of admins might
use several of them for dierent purposes.
Permanent Test Environments
In this pattern, you have a relatively stable group of test nodes in a permanent test environment,
where all changes must succeed before they can be merged into your production code.
The test nodes probably closely resemble the whole production infrastructure in miniature. They
might be short-lived cloud instances, or longer-lived VMs in a private cloud. Theyll probably stay in
the test environment for their whole lifespan.
Temporary Test Environments
In this pattern, developers and admins can create temporary environments to test out a single
change or group of changes. This usually means doing a fresh checkout from your version control
into the $confdir/environments directory, where it will be detected as a new environment. These
environments might have descriptive names, or might just use the commit IDs from the version of
the code theyre based on.
Puppet 3.6 Reference Manual Environments: Suggestions for Use 255/325
Temporary environments are good for testing individual changes, especially if you need to iterate
quickly while developing them. Since its easy to create many of them, you dont have to worry
about coordinating with other developers and admins the way you would with a monolithic test
environment; everyone can have a personal environment for their current development work.
Once youre done with a temporary environment, you can delete it. Usually, the nodes in a
temporary environment will be short-lived cloud instances or VMs, which can be destroyed when
the environment ends; otherwise, youll need to move the nodes back into a stable environment.
This pattern works best with directory environments. If you need to use temporary cong le
environments, you can use the pattern from Adrien Thebos blog post on the subject.
Divided Infrastructure
If parts of your infrastructure are managed by dierent teams that dont need to coordinate their
code, it may make sense to split them into environments.
Environments: Limitations of Environments
Environments solve a lot of problems in a convenient way, but they still have some limitations. Some
of these are just features Puppet doesnt have yet, and some of them are outside Puppets control.
We want to x all of them, but some may take a lot longer than others.
Plugins Running on the Puppet Master are Weird
Puppet modules can contain Puppet code, templates, le sources, and Ruby plugin code (in the lib
directory). Environments work perfectly with most of those, but theres a lingering problem with
plugins.
The short version is: any plugins destined for the agent node (e.g. custom facts and custom
resource providers) will work ne, but plugins to be used by the puppet master (functions, resource
types, report processers, indirector termini) can get mixed up, and you wont be able to control
which version the puppet master is using. So if you need to do testing while developing custom
resource types or functions, you may need to spin up a second puppet master, since environments
wont be reliable.
This has to do with the way Ruby loads code, and were not sure if it can be xed given Puppets
current architecture. (Some of us think this would require separate Ruby puppet master processes
for each environment, which isnt currently practical with the way Rack manages Puppet.)
If youre interested in the issue, its being tracked as PUP-731.
Hiera Conguration Cant be Specied Per Environment
Puppet 3.6 Reference Manual Environments: Limitations of Environments 256/325
Puppet will only use a global hiera.yaml le; you cant put per-environment congs in an
environment directory.
When using the built-in YAML or JSON backends, it is possible to separate your Hiera data per
environment; you will need to interpolate the $environment variable into the :datadir setting.
(e.g. :datadir: /etc/puppet/environments/%{::environment}/hieradata)
Most Extensions Arent Environment-Aware
As of today, most extensions to Puppet (including PuppetDB and the Puppet Enterprise console)
dont receive, store, or control information about Puppets use of environments.
Were in the process of working on this; one of the most important steps was adding the ability to
query the master for environment info, as mentioned above.
Exported Resources Can Conict or Cross Over
Nodes in one environment can accidentally collect resources that were exported from another
environment, which causes problems either a compilation error due to identically titled
resources, or creation and management of unintended resources.
Right now, the only solution is to run multiple puppet masters if you heavily use exported
resources. Were working on making PuppetDB environment-aware, which will x the problem in a
more permanent way.
Environments and Puppet's HTTPS Interface
Puppets environments interact in several ways with Puppets HTTPS interface.
Environments are Embedded in Puppets HTTPS Requests
Puppets agent and master applications communicate via an HTTP API. All of the URLs used today by
puppet agent (the v1 API) start with an environment. See the HTTP API reference for details.
For some endpoints, making a request in an environment is meaningless; for others, it inuences
which modules and manifests the conguration data will come from. Regardless, the API dictates
that an environment always be included.
Endpoints where the requested environment can be overridden by the ENC/node terminus:
Catalog For this endpoint, the environment is just a request, as described above in the section
on assigning nodes to environments; if the ENC species an environment for the node, it will
override the environment in the request.
Endpoints where the requested environment is always used:
Puppet 3.6 Reference Manual Environments and Puppet's HTTPS Interface 257/325
File content and le metadata Files in modules, including plugins like custom facts and
resource types, will always be served from the requested environment. Puppet agent has to
account for this when fetching les; it does so by fetching its node object (see node below),
then resetting the environment it will request to whatever the ENC specied and using that new
environment for all subsequent requests. (Since custom facts might inuence the decision of the
ENC, the agent will repeat this process up to three times before giving up.)
Resource type Puppet agent doesnt use this; its just for extensions. The puppet master will
always respond with information for the requested environment.
Endpoints where environment makes no dierence:
File Bucket File Theres only one lebucket.)
Report Reports already contain environment info, and each report handler can decide what, if
anything, to do with it.)
Facts Puppet agent doesnt actually use this endpoint. When used as the inventory service,
environment has no eect.)
Node Puppet agent uses this to learn whether the masters ENC has overridden its preferred
environment. Theoretically, a node terminus could use the environment of the rst node object
request to decide whether to override the environment, but were not aware of anyone doing
that and there wouldnt seem to be much point to it.)
Status
Certicate, certicate signing request, certicate status, and certicate revocation list The CA
doesnt dier by environment.)
Controlling HTTPS Access Based on Environment
The puppet masters auth.conf lecan use the environment of a request to help decide whether to
authorize a request. This generally isnt necessary or useful, but its there if the need arises. See the
auth.conf documentation for details.
You Can Query Environment Info via the Masters HTTP
API
If you are extending Puppet and need a way to query information about the available environments,
you can do this via the environments endpoint. (This endpoint uses the new v2 HTTP API.)
This only works for directory environments. When you query environments via the API, any cong
le environmentswill be omitted.
For more details, see the reference page about the environments endpoint.
Conguration: How Puppet is Congured
Puppets commands and services can be extensively congured, and its settings can be specied in
Puppet 3.6 Reference Manual Conguration: How Puppet is Congured 258/325
a variety of places.
This page is an overview of how Puppets conguration works.
How Puppet Loads Settings
What are These Settings?
Here they are:
The short list of useful settings
The complete list of settings (AKA the conguration reference)
Settings are Loaded on Startup
When any Puppet command or service starts up, it gets values for all of its settings. Any of these
settings may change the way that command or service behaves.
A command or service will only read its settings once; if it needs to be recongured, it will need to
be restarted or run again.
Settings can be set on the Command Line
When a Puppet command or service is started, you can specify any setting as a command line
option, using two hyphens and the name of the setting:
$ sudo puppet agent --test --noop --certname temporary-name.example.com
Settings from the command line have top priority, and will always override settings from the cong
le.
(When running under Rack, the puppet master service can have command line options set in its
config.ru le. For the puppet agent service, you can often edit the init script to add command line
options. In both cases, this is really only useful for the confdir and vardir settings, which cant be
set in puppet.conf.)
BASIC SETTINGS
For most settings, you specify the option and follow it with a value. An equals sign between the two
( =) is optional, and values may optionally be surrounded by quotes.
--certname=temporary-name.example.com
--certname temporary-name.example.com
--certname "temporary-name.example.com"
All three of these are equivalent to setting certname = temporary-name.example.com in
puppet.conf.
Puppet 3.6 Reference Manual Conguration: How Puppet is Congured 259/325
puppet.conf.
BOOLEAN SETTINGS
For settings whose only valid values are true and false, you use a shorter format instead. Specify
the option alone to set the setting to true, or prex the option with no- to set it to false. That is:
--noop is equivalent to setting noop = true in puppet.conf.
--no-noop is equivalent to setting noop = false in puppet.conf.
Settings can be set in the Main Cong File
Puppets main cong le is called puppet.conf. Its format and behavior are described in full on a
separate page.
Settings Have Default Values
If a setting isnt specied on the command line or in puppet.conf, it will fall back to a default value.
Default values for all settings are listed in the conguration reference.
Some of these default values are based on other settings when this is the case, the default is
shown using the other setting as a variable (e.g. $ssldir/certs).
Main Settings vs. Extra Cong Files
When we mention settings in the context of Puppet, we usually mean the main settings. These are
the settings that are listed in the conguration reference (short list, long list). They are valid in
puppet.conf and available for use on the command line. These settings congure nearly all of
Puppets core features.
However, there are also about nine extra conguration les things like auth.conf and
puppetdb.conf. These les exist for several reasons:
The main settings only support a few types of values. Some things just cant be congured
without complex data structures, so they needed separate les. (Authorization rules and custom
CSR attributes are in this category.)
Puppet currently doesnt allow extensions to add new settings to puppet.conf. This means some
settings that should be main settings (like the PuppetDB server) cant be.
Conguration: Checking Values of Settings
Puppet settings are highly dynamic, and their values can come from several dierent places.
To see the actual settings values that a Puppet service will use, its often best to ask Puppet itself.
The puppet config print command lets you do this.
Puppet 3.6 Reference Manual Conguration: Checking Values of Settings 260/325
General Usage
The puppet config print command loads and evaluates settings, and can imitate any of Puppets
other commands and services when doing so. The --section and --environment options let you
control how settings are loaded; for details, see the sections below on imitating dierent services.
TO SEE THE VALUE OF ONE SETTING:
$ sudo puppet config print <SETTING NAME> [--section <CONFIG SECTION>] [--
environment <ENVIRONMENT>]
This will show just the value of <SETTING NAME>.
TO SEE THE VALUE OF MULTIPLE SETTINGS:
$ sudo puppet config print <SETTING 1> <SETTING 2> [...] [--section <CONFIG
SECTION>] [--environment <ENVIRONMENT>]
This will show name = value pairs for all requested settings.
TO SEE THE VALUE OF ALL SETTINGS:
$ sudo puppet config print [--section <CONFIG SECTION>] [--environment
<ENVIRONMENT>]
This will show name = value pairs for all settings.
Cong Sections
The --section option species which section of puppet.conf to use when nding settings. It is
optional, and defaults to main. Valid sections are:
main (default) used by all commands and services
master used by the puppet master service and the puppet cert command
agent used by the puppet agent service
user used by the puppet apply command and most other commands
As usual, the other sections will override the main section if they contain a setting; if they dont, the
Note: To ensure that youre seeing the values Puppet will use when running as a service, be
sure to use sudo or run the command as root or Administrator. If you run puppet config
print as some other user, Puppet might not use the system cong le.
Puppet 3.6 Reference Manual Conguration: Checking Values of Settings 261/325
value from main will be used, or a default value if the setting isnt present there.
Environments
The --environment option species which environment use when nding settings. It is optional,
and defaults to the value of the environment setting in the user section (usually production, since
its rare to specify an environment in user).
Any valid environment can be specied, including environments that dont exist or dont have any
settings congured.
This option is generally only useful when looking up settings used by the puppet master service,
since its rare to use environment cong sections for puppet apply and puppet agent.
Imitating Puppet Master and Puppet Cert
To see the settings the puppet master service and the puppet cert command would use:
Specify --section master.
Use the --environment option to specify the environment you want settings for, or let it default
to production.
Remember to use sudo.
If your puppet master is managed as a rack application (e.g. with Passenger), check the
config.ru le to make sure its using the confdir and vardir that you expect. If its using non-
standard ones, you will need to specify them on the command line with the --confdir and --
vardir options; otherwise you may not see the correct values for settings.
Examples
To see the eective modulepath used in the dev environment:
$ sudo puppet config print modulepath --section master --environment dev
/etc/puppetlabs/puppet/environments/dev/modules:/etc/puppetlabs/puppet/modules:/opt/puppet/share/puppet/modules
To see whether the $facts and $trusted variables are enabled:
$ sudo puppet config print trusted_node_data immutable_node_data --section
master
trusted_node_data = true
immutable_node_data = true
Imitating Puppet Agent
Puppet 3.6 Reference Manual Conguration: Checking Values of Settings 262/325
To see the settings the puppet agent service would use:
Specify --section agent.
Remember to use sudo.
If you are seeing something unexpected, check your puppet agent init script or cron job to make
sure it is using the standard confdir and vardir, is running as root, and isnt overriding other
settings with command line options. If its doing anything unusual, you may have to set more
options for the cong print command.
Example
To see whether the agent is congured to use manifest ordering when applying the catalog:
$ sudo puppet config print ordering --section agent
manifest
Imitating Puppet Apply
To see the settings the puppet apply command would use:
Specify --section user.
Remember to use sudo.
If you are seeing something unexpected, check the cron job or script that is responsible for
conguring the machine with puppet apply. Make sure it is using the standard confdir and
vardir, is running as root, and isnt overriding other settings with command line options. If its
doing anything unusual, you may have to set more options for the cong print command.
Example
To see whether puppet apply is congured to use reports:
$ sudo puppet config print report reports --section user
report = true
reports = store,http
Compatibility Note / Alternate Usage
Prior to Puppet 3.5 and Puppet Enterprise 3.2, the puppet config print command wasnt exible
enough to imitate all of Puppets applications and services. Instead, you would need to use one of
the following commands:
puppet master --configprint <SETTING>
puppet agent --configprint <SETTING>
puppet apply --configprint <SETTING>
Puppet 3.6 Reference Manual Conguration: Checking Values of Settings 263/325
These behave much the same as the current behavior of puppet config print, and still work with
this version of Puppet.
Conguration: Changing Settings on the
Command Line
Puppet loads most of its settings from the puppet.conf cong le.You can edit this le directly, or
you can change individual settings with the puppet config set command.
Usage
To assign a new value to a setting, run:
$ sudo puppet config set <SETTING NAME> <VALUE> --section <CONFIG SECTION>
This will declaratively set the value of <SETTING NAME> to <VALUE> (in the specied cong section).
It will work the same way regardless of whether the setting already had a value.
Cong Sections
The --section option species which section of puppet.conf to modify. It is optional, and defaults
to main. Valid sections are:
main (default) used by all commands and services
master used by the puppet master service and the puppet cert command
agent used by the puppet agent service
user used by the puppet apply command and most other commands
Any valid environment name used by all commands and services when requesting or
compiling catalogs in that environment
When to Use This
We recommend using puppet config set for:
Fast one-o cong changes
Scriptable cong changes in provisioning tools
If you nd yourself changing many settings at once, you might prefer to edit the puppet.conf
le or manage it with a template.
Puppet 3.6 Reference Manual Conguration: Changing Settings on the Command Line 264/325
If modifying the system cong le, be sure to use sudo or run the command as root or
Administrator.
Example
Before:
# /etc/puppetlabs/puppet/puppet.conf
[main]
certname = agent01.example.com
server = master.example.com
vardir = /var/opt/lib/pe-puppet
[agent]
report = true
graph = true
pluginsync = true
[master]
dns_alt_names = master,master.example.com,puppet,puppet.example.com
Commands:
$ sudo puppet config set trusted_node_data true --section master
$ sudo puppet config set ordering manifest
After:
# /etc/puppetlabs/puppet/puppet.conf
[main]
certname = agent01.example.com
server = master.example.com
vardir = /var/opt/lib/pe-puppet
ordering = manifest
[agent]
report = true
graph = true
pluginsync = true
[master]
dns_alt_names = master,master.example.com,puppet,puppet.example.com
trusted_node_data = true
Compatibility Note
The puppet config set command rst appeared in Puppet 3.5 and Puppet Enterprise 3.2. It cant
Puppet 3.6 Reference Manual Conguration: Changing Settings on the Command Line 265/325
be used with earlier versions of Puppet.
Conguration: Short List of Important
Settings
Puppet has about 230 settings, all of which are listed in the conguration reference. Most users can
ignore about 200 of those.
This page lists the most important ones. (We assume here that youre okay with default values for
things like the port Puppet uses for network trac.) The link for each setting will go to the long
description in the conguration reference.
Getting New Features Early
Weve added improved behavior to Puppet over the course of the 3.x series, but some of it cant be
enabled by default until a major version boundary, since it changes things that some users might
be relying on. But if you know your site wont be aected, you can enable some of it today.
Recommended and Safe
trusted_node_data = true (puppet master/apply only) This enables the $trusted and
$facts hashes, so you can start using them in your own code.
And then the $facts variable can be independently disabled with the immutable_node_data
setting, but you probably want both.
stringify_facts = false (all nodes) This enables structured facts, allowing facts to contain
arrays, hashes, and booleans instead of just strings. This requires Facter 2.0, and none of the
core facts use this yet, but enabling it will let you take advantage of structured facts as they are
gradually released.
ordering = manifest (all nodes) This causes unrelated resources to be applied in the order
they are written, instead of in eectively random order. It allows you to be lazy in small classes
and write resources in chronological order instead of specifying dependencies. But be careful
when writing manifests like this, since it makes it harder to share code with other users.
Why so many settings? There are a lot of settings that are rarely useful but still make sense,
but there are also at least a hundred that shouldnt be congurable at all.
This is basically a historical accident. Due to the way Puppets code is arranged, the settings
system was always the easiest way to publish global constants that are dynamically initialized
on startup. This means a lot of things have crept in there regardless of whether they needed
to be congurable.
Puppet 3.6 Reference Manual Conguration: Short List of Important Settings 266/325
Possibly Disruptive
Both of these only aect the puppet master (and puppet apply nodes).
parser = future (puppet master/apply only) This enables the future parser, which is
explained in more detail on the future parser page. Since it swaps out the entire Puppet
language, theres a good chance youll nd something in your code it doesnt like, but it now
runs at a decent speed and lets you explore whats eventually coming in Puppet 4.
strict_variables = true (puppet master/apply only) This makes uninitialized variables
cause parse errors, which can help squash dicult bugs by failing early instead of carrying undef
values into places that dont expect them. This one has a strong chance of causing problems
when you turn it on, so be wary, but it will eventually improve the general quality of Puppet code.
Settings for Agents (All Nodes)
Roughly in order of importance. Most of these can go in either [main] or [agent], or be specied
on the command line.
Basics
server The puppet master server to request congurations from. Defaults to puppet; change
it if thats not your servers name.
ca_server and report_server If youre using multiple masters, youll need to centralize
the CA; one of the ways to do this is by conguring ca_server on all agents. See the multiple
masters guide for more details. The report_server setting works about the same way,
although whether you need to use it depends on how youre processing reports.
certname The nodes certicate name, and the name it uses when requesting catalogs;
defaults to the fully qualied domain name.
For best compatibility, you should limit the value of certname to only use letters, numbers,
periods, underscores, and dashes. (That is, it should match /\A[a-z0-9._-]+\Z/.)
The special value ca is reserved, and cant be used as the certname for a normal node.
(Yes, its also possible to re-use certicates/certnames and then set the name used in
requests via the node_name_fact / node_name_value settings. Dont do this unless you know
exactly what youre doing, because it changes Puppets whole security model. For most users,
certname = only name.)
environment The environment to request when contacting the puppet master. Its only a
request, though; the masters ENC can override this if it chooses. Defaults to production.
Run Behavior
These settings aect the way Puppet applies catalogs.
noop If enabled, the agent wont do any work; instead, it will look for changes that should be
made, then report to the master about what it would have done. This can be overridden per-
Puppet 3.6 Reference Manual Conguration: Short List of Important Settings 267/325
resource with the noop metaparameter.
priority Allows you to nice puppet agent so it wont starve other applications of CPU
resources while its applying a catalog.
report Whether to send reports. Defaults to true; usually shouldnt be disabled, but you might
have a reason.
tags Lets you limit the Puppet run to only include resources with certain tags.
trace, profile, graph, and show_diff Tools for debugging or learning more about an agent
run. Extra-useful when combined with the --test and --debug CLI options.
usecacheonfailure Whether to fall back to the last known good catalog if the master fails to
return a good catalog. The default behavior is good, but you might have a reason to disable it.
ignoreschedules If you use schedules, this can be useful when doing an initial Puppet run to
set up new nodes.
prerun_command and postrun_command Commands to run on either side of a Puppet run.
pluginsync This defaults to true these days, so you dont need it in your cong le. But you
might see it in default cong les still, because in versions 2.7 you had to turn it on yourself.
Service Behavior
These settings aect the way puppet agent acts when running as a long-lived service.
runinterval How often to do a Puppet run, when running as a service.
waitforcert Whether to keep trying back if the agent cant initially get a certicate. The
default behavior is good, but you might have a reason to disable it.
Useful When Running Agent from Cron
splay and splaylimit Together, these allow you to spread out agent runs. When running the
agent as a daemon, the services will usually have been started far enough out of sync to make
this a non-issue, but its useful with cron agents. For example, if your agent cron job happens
on the hour, you could set splay = true and splaylimit = 60m to keep the master from
getting briey hammered and then left idle for the next 50 minutes.
daemonize Whether to daemonize. Set this to false when running the agent from cron.
onetime Whether to exit after nishing the current Puppet run. Set this to true when running
the agent from cron.
Settings for Puppet Master Servers
Many of these settings are also important for standalone puppet apply nodes, since they act as their
own puppet master.
These settings should usually go in [master]. However, if youre using puppet apply in production,
put them in [main] instead.
Puppet 3.6 Reference Manual Conguration: Short List of Important Settings 268/325
Basics
dns_alt_names A list of hostnames the server is allowed to use when acting as a puppet
master. The hostname your agents use in their server setting must be included in either this
setting or the masters certname setting. Note that this setting is only used when initially
generating the puppet masters certicate if you need to change the DNS names, you must:
Turn o the puppet master service (or Rack server).
Run sudo puppet cert clean <MASTER'S CERTNAME>.
Run sudo puppet cert generate <MASTER'S CERTNAME> --dns_alt_names <ALT NAME
1>,<ALT NAME 2>,....
Re-start the puppet master service.
environmentpath Set this to $confdir/environments to enable directory environments. See
the page on directory environments for details.
basemodulepath A list of directories containing Puppet modules that can be used in all
environments. See the modulepath page for details.
If directory environments are disabled, the modulepath setting controls the nal modulepath.
You can also set modulepath in environment.conf.
manifest The main entry point for compiling catalogs. This is only used if directory
environments arent enabled. Defaults to a single site.pp le, but can also point to a directory of
manifests. See the manifest page for details.
reports Which report handlers to use. For a list of available report handlers, see the report
reference. You can also write your own report handlers. Note that the report handlers might
require settings of their own, like tagmails various email settings.
Rack-Related Settings
ssl_client_header and ssl_client_verify_header These are used when running puppet
master as a Rack application (e.g. under Passenger), which you should denitely be doing. See
the Passenger setup guide for more context about how these settings work; depending on how
you congure your Rack server, you can usually leave these settings with their default values.
Extensions
These features congure add-ons and optional features.
node_terminus and external_nodes The ENC settings. If youre using an ENC, set these to
exec and the path to your ENC script, respectively.
storeconfigs and storeconfigs_backend Used for setting up PuppetDB. See the PuppetDB
docs for details.
catalog_terminus This can enable the optional static compiler. If you have lots of file
resources in your manifests, the static compiler lets you sacrice some extra CPU work on your
puppet master to gain faster conguration and reduced HTTPS trac on your agents. See the
Puppet 3.6 Reference Manual Conguration: Short List of Important Settings 269/325
static compiler section of the indirection reference for details.
config_version The cong version is an ID string included in catalogs and reports. Usually
its just the time at which the catalog was compiled, but this setting can specify a command to
run to generate that ID. Some people use this to get, e.g., the current git HEAD in their modules
directory.
CA Settings
ca Whether to act as a CA. There should only be one CA at a Puppet deployment. If youre
using multiple puppet masters, youll need to set ca = false on all but one of them.
ca_ttl How long newly signed certicates should be valid for.
autosign Whether (and how) to autosign certicates. See the autosigning page for details.
Cong Files: The Main Cong File
(puppet.conf)
The puppet.conf le is Puppets main cong le. It congures all of the Puppet commands and
services, including puppet agent, puppet master, puppet apply, and puppet cert. Nearly all of the
settings listed in the conguration referencecan be set in puppet.conf.
It resembles a standard INI le, with a few syntax extensions. Settings may go into application-
specic sections, or into a [main] section that aects all applications.
(Useful background info: about settings, short list of settings, full list of settings.)
Location
The puppet.conf le is always located at $confdir/puppet.conf.
Although its location is congurable with the config setting, it can only be set on the command
line (e.g. puppet agent -t --config ./temporary_config.conf).
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Example
# Settings in [main] are used if a more specific section doesn't set a value.
[main]
certname = puppetmaster01.example.com
logdir = /var/log/pe-puppet
rundir = /var/run/pe-puppet
modulepath =
/etc/puppetlabs/puppet/modules:/opt/puppet/share/puppet/modules
Puppet 3.6 Reference Manual Cong Files: The Main Cong File (puppet.conf) 270/325
server = puppet.example.com
user = pe-puppet
group = pe-puppet
archive_files = true
archive_file_server = puppet.example.com
# This section is used by the puppet master and puppet cert applications.
[master]
certname = puppetmaster01.example.com
dns_alt_names =
puppetmaster01,puppetmaster01.example.com,puppet,puppet.example.com
ca_name = 'Puppet CA generated on puppetmaster01.example.com at 2013-08-09
19:11:11 +0000'
reports = http,puppetdb
reporturl = https://localhost:443/reports/upload
node_terminus = exec
external_nodes = /etc/puppetlabs/puppet-dashboard/external_node
ssl_client_header = SSL_CLIENT_S_DN
ssl_client_verify_header = SSL_CLIENT_VERIFY
storeconfigs_backend = puppetdb
storeconfigs = true
autosign = true
# This section is used by the puppet agent application.
[agent]
report = true
classfile = $vardir/classes.txt
localconfig = $vardir/localconfig
graph = true
pluginsync = true
environment = production
Format
The puppet.conf le consists of one or more cong sections,each of which may contain any
number of settings.
The le may also include comment lines at any point.
Cong Sections
[main]
certname = puppetmaster01.example.com
A cong section is a group of settings. It consists of:
Its name, enclosed in square brackets. The [name] of the cong section must be on its own line,
with no leading space.
Any number of setting lines, which may be indented for readability.
Any number of empty lines or comment lines.
Puppet 3.6 Reference Manual Cong Files: The Main Cong File (puppet.conf) 271/325
As soon as a new cong section [name] appears in the le, the former cong section is closed and
the new one begins. A given cong section should only occur once in the le.
The Primary Cong Sections
Puppet uses four primary cong sections:
main is the global section used by all commands and services. It can be overridden by the other
sections.
master is used by the puppet master service and the puppet cert command.
agent is used by the puppet agent service.
user is used by the puppet apply command, as well as many of the less common Puppet
subcommands.
Puppet will prefer to use settings from one of the three application-specic sections (master,
agent, or user). If it doesnt nd a setting in the application section, it will use the value from main.
(If main doesnt set one, it will fall back to the default value.)
Environment Cong Sections
[test]
modulepath =
$confdir/environments/test/modules:$condfir/modules:/usr/share/puppet/modules
manifest = $confdir/environments/test/manifests
If you are using cong le environments, each environment can have its own cong section. See the
page on cong le environmentsfor details.
If it exists, the environment cong section for the active environment always has highest priority.
That is, it will override settings from the master section while the puppet master is serving agents
assigned to that environment.
Comment Lines
# This is a comment.
Comment lines start with a hash sign ( #). They may be indented with any amount of leading space.
Partial-line comments (e.g. report = true # this enables reporting) are not allowed, and will
be treated as part of the value of the setting. To be treated as a comment, the hash sign must be
the rst non-space character on the line.
Setting Lines
Puppet 3.6 Reference Manual Cong Files: The Main Cong File (puppet.conf) 272/325
certname = puppetmaster01.example.com
A setting line consists of:
Any amount of leading space (optional).
The name of a setting.
An equals sign ( =), which may optionally be surrounded by any number of spaces.
A value for the setting.
Special Types of Values for Settings
Generally, the value of a setting will be a single word. However, there are a few special types of
values:
LISTS OF WORDS
Some settings (like reports) can accept multiple values, which should be specied as a comma-
separated list (with optional spaces after commas). Example: report = http,puppetdb
PATHS
Some settings (like modulepath or [ environmentpath]) take a list of directories. The directories
should be separated by the system path separator character, which is colon ( :) on *nix platforms
and semicolon ( ;) on Windows.
# *nix version:
modulepath = $confdir/modules:/opt/usr/share/puppet/modules
# Windows version:
modulepath = $confdir/modules;C:/Users/Administrator/global_modules
Path lists are ordered; Puppet will always check the rst directory rst, then move on to the others if
it doesnt nd what it needs.
FILES OR DIRECTORIES
Settings that take a single le or directory (like ssldir) can accept an optional hash of permissions.
When starting up, Puppet will enforce those permissions on the le or directory.
You generally shouldnt do this, as the defaults are good for most users. However, if you need to,
you can specify permissions by putting a hash like this after the path:
ssldir = $vardir/ssl {owner = service, mode = 0771}
The allowed keys in the hash are owner, group, and mode. There are only two valid values for the
owner and group keys:
root the root or Administrator user or group should own the le.
Puppet 3.6 Reference Manual Cong Files: The Main Cong File (puppet.conf) 273/325
service the user or group that the Puppet service is running as should own the le. (The
services user and group are specied by the user and group settings. On a puppet master
running open source Puppet, these default to puppet; on Puppet Enterprise they default to pe-
puppet.)
Interpolating Variables in Settings
The values of settings are available as variables within puppet.conf, and you can insert them into
the values of other settings. To reference a setting as a variable, prex its name with a dollar sign
( $):
ssldir = $vardir/ssl
However, not every setting can be safely interpolated into other settings; since the order in which
Puppet evaluates its settings can be somewhat opaque, its possible that a settings value wont be
initialized by the time you reference it. In general, you should only interpolate the following
variables:
$confdir
$vardir
$environment (When used on the puppet master, this always refers to the agents environment,
and should only be used in the manifest and modulepath settings. Use of this variable isnt
technically deprecated yet, but it will be soon. See the page on cong le environmentsfor
details, and the page on directory environments for the easier system that replaces it.)
Cong Files: auth.conf
Access to Puppets HTTPS API is congured in auth.conf.
About Puppets HTTPS API
When running in the standard agent/master arrangement, puppet agent nodes receive all of their
congurations by contacting the puppet master over HTTPS. In general, a single conguration run
includes:
Fetching a node object (to read the nodes environment)
Fetching plugins
Requesting a catalog (and submitting the nodes facts as POST data in the request)
Fetching le metadata and contents while applying the catalog
Submitting a report after applying the catalog
All of these are provided as HTTPS services (sometimes called endpoints) by the puppet master
Puppet 3.6 Reference Manual Cong Files: auth.conf 274/325
server. Additionally, the puppet master provides other services, some of which are used less
frequently by agent nodes (such as the CA services) and some of which shouldnt be used by agent
nodes at all (such as the certificate_status service, which can sign and revoke certicates).
Since not all agent nodes should have access to all services, and since certain services should have
restricted access (for example, nodes should not be able to request some other nodes
conguration catalog), the puppet master keeps a list of access rules for all of its HTTPS services.
These rules can be edited in auth.conf.
Location
The auth.conf le is located at $confdir/auth.conf by default. Its location is congurable with
the rest_authconfig setting.
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Example
# Example auth.conf:
path /
auth true
environment override
allow magpie.example.com
path /certificate_status
auth true
environment production
allow magpie.example.com
path /facts
method save
auth true
allow magpie.example.com
path /facts
auth true
method find, search
allow magpie.example.com, dashboard.example.com, finch.example.com
Format
See the HTTPS access control documentation for full details about the auth.conf le.
Puppet 3.6 Reference Manual Cong Files: auth.conf 275/325
Cong Files: autosign.conf
The autosign.conf le can allow certain certicate requests to be automatically signed. It is only
valid on the CA puppet master server; a puppet master that is not serving as a CA will not consult
autosign.conf.
More About Autosigning
Puppet also provides a policy-based interface for autosigning, which can be more exible and
secure. The autosign.conf le is the simpler and less secure method.
For more details, see the reference page about certicate autosigning.
Location
The autosign.conf le is located at $confdir/autosign.conf by default. Its location is
congurable with the autosign setting.
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Format
The autosign.conf le is a list of certnames or domain name globs (one per line). Each line
represents a node name or group of node names whose certicate requests should be
automatically signed when the CA puppet master receives them.
rebuilt.example.com
*.scratch.example.com
*.local
Note that domain name globs do not function as normal globs: an asterisk can only represent one
or more subdomains at the front of a certname that resembles a fully-qualied domain name. (That
is, if your certnames dont look like FQDNs, you cant use autosign.conf to full eect.
Note: Since any host can request any certname, autosigning with autosign.conf is essentially
insecure. See the reference page about certicate autosigningfor more context.
Cong Files: csr_attributes.yaml
The csr_attributes.yaml le denes custom data for new certicate signing requests (CSRs). It
can set:
Puppet 3.6 Reference Manual Cong Files: autosign.conf 276/325
CSR attributes (transient data used for pre-validating requests)
Certicate extension requests (permanent data to be embedded in a signed certicate)
This le is only consulted when a new CSR is created (e.g. when an agent node is rst attempting to
join a Puppet deployment). It cannot modify existing certicates.
Location
The csr_attributes.yaml le is located at $confdir/csr_attributes.yaml by default. Its location
is congurable with the csr_attributes setting.
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Example
---
custom_attributes:
1.2.840.113549.1.9.7: 342thbjkt82094y0uthhor289jnqthpc2290
extension_requests:
pp_uuid: ED803750-E3C7-44F5-BB08-41A04433FE2E
pp_image_name: my_ami_image
pp_preshared_key: 342thbjkt82094y0uthhor289jnqthpc2290
Format
The csr_attributes le must be a YAML hash containing one or both of the following keys:
custom_attributes
extension_requests
The value of each key must also be a hash, where:
Each key is a valid object identier (OID). Note that Puppet-specic OIDsmay optionally be
referenced by short name instead of by numeric ID. (In the example above, pp_uuid is a short
name for a Puppet-specic OID.)
Each value is an object that can be cast to a string (that is, numbers are allowed but arrays are
not).
Allowed OIDs for Custom Attributes
Note: For details on how to use this le, see the documentation for CSR attributes and
certicate extensions.
Puppet 3.6 Reference Manual Cong Files: autosign.conf 277/325
Custom attributes can use any public or site-specic OID, with the exception of the OIDs used for
core X.509 functionality. This means you cant re-use existing OIDs for things like subject
alternative names.
One useful OID is the challengePassword attribute 1.2.840.113549.1.9.7. This is a rarely-
used corner of X.509 which can easily be repurposed to hold a pre-shared key. The benet of using
this instead of an arbitrary OID is that it will appear by name when using OpenSSL to dump the CSR
to text; OIDs that openssl req cant recognize will be displayed as numerical strings.
Also note that the Puppet-specic OIDs listed below can also be used in CSR attributes.
Allowed OIDs for Extension Requests
Extension request OIDs must be under the ppRegCertExt ( 1.3.6.1.4.1.34380.1.1) or
ppPrivCertExt ( 1.3.6.1.4.1.34380.1.2) OID arcs.
Puppet Labs provides several registered OIDs (under ppRegCertExt) for the most common kinds
of extension information, as well as a private OID range (ppPrivCertExt) for site-specic extension
information. The benets of using the registered OIDs are:
They can be referenced in csr_attributes.yaml using their short names instead of their
numeric IDs.
When using Puppet tools to print certicate info, they will appear using their descriptive names
instead of their numeric IDs.
The private range is available for any information you want to embed into a certicate that isnt
already in wide use elsewhere. It is completely unregulated, and its contents are expected to be
dierent in every Puppet deployment.
PUPPET-SPECIFIC REGISTERED IDS
The ppRegCertExt OID range contains the following OIDs:
Numeric ID Short Name Descriptive Name
1.3.6.1.4.1.34380.1.1.1 pp_uuid Puppet Node UUID
1.3.6.1.4.1.34380.1.1.2 pp_instance_id Puppet Node Instance ID
1.3.6.1.4.1.34380.1.1.3 pp_image_name Puppet Node Image Name
1.3.6.1.4.1.34380.1.1.4 pp_preshared_key Puppet Node Preshared Key
Cong Files: device.conf
The puppet device subcommand congures network hardware using a catalog downloaded from
the puppet master; in order to function, it requires that the relevant devices be congured.
Puppet 3.6 Reference Manual Cong Files: device.conf 278/325
Location
The device.conf le is located at $confdir/device.conf by default. Its location is congurable
with the deviceconfig setting.
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Format
device.conf is organized in INI-like sections, with one section per device:
[router6.example.com]
type cisco
url ssh://admin:[email protected]
The name of each section should be the name that will be used with puppet device to access the
device.
The body of the section should contain a type directive (the only current valid value is cisco) and a
url directive (which should be an SSH URL to the devices management interface).
Cong Files: environment.conf
When using directory environments, each environment may contain an environment.conf le. This
le can override several settings whenever the puppet master is serving nodes assigned to that
environment.
Location
Each environment.conf le should be stored in a directory environment. It should be at the top level
of its home environment, next to the manifests and modules directories.
For example: if your environmentpath setting is set to $confdir/environments, the
environment.conf le for the test environment should be located at
$confdir/environments/test/environment.conf.
Example
# /etc/puppetlabs/puppet/environments/test/environment.conf
# Exclude global directories in basemodulepath from this environment:
modulepath = modules
Puppet 3.6 Reference Manual Cong Files: environment.conf 279/325
# Use our custom script to get a git commit for the current state of the code:
config_version = get_environment_commit.sh
Format
The environment.conf le uses the same INI-like format as puppet.conf, with one exception: it
cannot contain cong sections like [main]. All settings in environment.conf must be outside any
cong section.
Allowed Settings
In this version of Puppet, the environment.conf le is only allowed to override four settings:
modulepath
manifest
config_version
environment_timeout
Relative Paths in Values
Most of the allowed settings accept le paths or lists of paths as their values.
If any of these paths are relative paths that is, they start without a leading slash or drive letter
they will be resolved relative to that environments main directory.
RELATIVE PATH EXAMPLES
The example environment.conf le above congures an environment called test, which is located
in $confdir/environments. This means:
The modulepath = modules line will resolve to modulepath =
/etc/puppetlabs/puppet/environments/test/modules. This removes all of the global
directories inherited from the basemodulepath setting, and limits the environment to only its
local modules.
Likewise, config_version = get_environment_commit.sh in that environment will be
interpreted as config_version =
/etc/puppetlabs/puppet/environments/test/get_environment_commit.sh
Interpolation and $environment
Settings in environment.conf can use the special $environment variable in their values. Puppet will
replace $environment with the name of the active environment.
This is almost never necessary for modulepath or manifest, but it can be useful as an argument to
your config_version script.
Puppet 3.6 Reference Manual Cong Files: environment.conf 280/325
Settings in environment.conf can also interpolate other settings as variables, such as $confdir.
Cong Files: leserver.conf
The fileserver.conf le congures custom static mount points for Puppets le server. If custom
mount points are present, file resources can access them with their source attributes.
When to Use fileserver.conf
By default, fileserver.conf isnt necessary Puppet automatically serves les from the files
directory of modules, and most users nd this sucient. (More info on serving les from modules
is available here.)
However, some use cases make custom mount points more attractive: for example, large les that
shouldnt be checked into version control along with your Puppet modules, or sensitive credentials
that likewise shouldnt go into version control.
Location
The fileserver.conf le is located at $confdir/fileserver.conf by default. Its location is
congurable with the fileserverconfig setting.
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Example
# Files in the /path/to/files directory will be served
# at puppet:///extra_files/.
[extra_files]
path /etc/puppetlabs/puppet/extra_files
allow *
This fileserver.conf le would create a new mount point named extra_files. The allow *
directive would leave access control to the main auth.conf le.
Format
A fileserver.conf le consists of a collection of mount-point stanzas, and looks like a hybrid of
puppet.conf and auth.conf. Each stanza should consist of:
A [mount_point_name], surrounded by square brackets. This will become the name used in
Puppet 3.6 Reference Manual Cong Files: leserver.conf 281/325
puppet:/// URLs for les in this mount point.
A path directive, pointing to an absolute path on disk. This is where the mount points les are
stored.
Any number of allow or deny directives. In this version of Puppet, we recommend using only a
allow * directive in fileserver.conf.
Security Directives
The allow and deny directives in a mount point stanza can be used to control which nodes may
access the les in it. However, this feature predates the auth.conf le used in this version of
Puppet, and we recommend against using it. If possible, you should keep all authorization rules
centralized in auth.conf. To do this, put a single allow * rule in each custom mount point.
By default, auth.conf will allow all agent nodes with valid certicates to access les, and will block
access for any client that doesnt have a certicate. For most use cases, this is good enough.
However, if you are serving sensitive credentials via custom mount points, you may wish to add
more restrictive rules to auth.conf. To do this, add a rule to auth.conf for each mount point.
These rules should begin with:
path ~ ^/file_(metadata|content)s?/NAME_OF_MOUNT_POINT/
You can then congure auth.conf restrictions as per normal.
For more information on how the old allow and deny directives in fileserver.conf work, see the
le serving documentation.
Cong Files: hiera.yaml
The hiera.yaml le is used to congure Hiera, which Puppet can use to look up data.
Location
The hiera.yaml le is located at $confdir/hiera.yaml by default. Its location is congurable with
the hiera_config setting.
When Puppet loads Hiera, it will use its own Hiera cong le instead of the global one (which is
usually located at /etc/hiera.yaml). If needed, you can point the hiera_config setting at the
global Hiera cong.
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Puppet 3.6 Reference Manual Cong Files: hiera.yaml 282/325
Example
---
:backends:
- yaml
- json
:yaml:
:datadir: /etc/puppet/hieradata
:json:
:datadir: /etc/puppet/hieradata
:hierarchy:
- "%{clientcert}"
- "%{datacenter}"
- "%{osfamily}"
- common
Format
See the Hiera documentation for full details about the hiera.yaml le.
Cong Files: puppetdb.conf
The puppetdb.conf le contains the hostname and port of the PuppetDB server. It is only used if
you are using PuppetDB and have connected your puppet master to it.
Location
The puppetdb.conf le is always located at $confdir/puppetdb.conf. Its location is not
congurable.
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Example
[main]
server = puppetdb.example.com
port = 8081
Format
The puppetdb.conf le uses the same INI-like format as puppet.conf, but only uses a [main]
section and only has two settings:
Puppet 3.6 Reference Manual Cong Files: puppetdb.conf 283/325
The server setting must be set to the hostname of the PuppetDB server.
The port setting must be set to the port of the PuppetDB server.
See the PuppetDB manual for more information.
Cong Files: routes.yaml
The routes.yaml le overrides conguration settings involving indirector termini, and allows
termini to be set in greater detail than puppet.conf allows.
Context
The routes.yaml le works around cong limitations in Puppets internals and makes it possible to
use certain extensions to Puppet, most notably PuppetDB. Most users shouldnt freely edit the le,
and should only make changes that are explicitly recommended by the setup instructions for the
extension they are trying to install.
Location
The routes.yaml le is located at $confdir/routes.yaml by default. Its location is congurable
with the route_file setting.
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Example
---
master:
facts:
terminus: puppetdb
cache: yaml
Format
The routes.yaml le should be a YAML hash.
Each top level key should be the name of a run mode ( master, agent, or user), and its value
should be another hash.
Each key of these second-level hashes should be the name of an indirection, and its value
should be another hash.
The only keys allowed in these third-level hashes are terminus and cache. The value of
Puppet 3.6 Reference Manual Cong Files: routes.yaml 284/325
each of these keys should be the name of a valid terminus for the indirection named above.
Cong Files: tagmail.conf
The tagmail.conf le congures the optional tagmail report processor.
What is the Tagmail Report Processor?
Puppet agent nodes can be congured to send reports to a puppet master server. The master will
then use its congured report processors to handle those reports.
The tagmail report processor sends targeted emails to dierent admin users whenever certain
resources are changed.
Enabling Tagmail
To enable tagmail, you must:
Enable reporting: On agent nodes (and puppet apply nodes), set report = true.
You can optionally specify a dierent puppet master for reports with the report_server
setting.
Enable the tagmail processor: On puppet masters (and puppet apply nodes), set reports =
tagmail.
Note that the reports setting accepts a list, so you can enable multiple report processors.
Congure email:On puppet masters (and puppet apply nodes), set the reportfrom email
address and a value for either smtpserver or sendmail.
Congure tags:On puppet masters (and puppet apply nodes), create a tagmail.conf le at the
location specied in the tagmap setting.
The tagmail.conf File
Location
The tagmail.conf le is located at $confdir/tagmail.conf by default. Its location is congurable
with the tagmap setting.
The location of the confdir varies; it depends on the OS, Puppet distribution, and user account.
See the confdir documentation for details.
Example
Puppet 3.6 Reference Manual Cong Files: tagmail.conf 285/325
all: [email protected]
webserver, !mailserver: [email protected]
emerg, crit: [email protected], [email protected], [email protected]
This tagmail.conf le will mail any resource events tagged with webserver but not with
mailserver to the httpadmins group; any emergency or critical events to to James, Zach, and Ben,
and all events to the log-archive group.
Format
The tagmail.conf le is series of lines. Each line should consists of:
A comma-separated list of tags and !negated tags; valid tags include:
Explicit tags
Class names
all, which is a special value matching all events
Any valid Puppet log level ( debug, info, notice, warning, err, alert, emerg, crit, or
verbose)
A colon
A comma-separated list of email addresses
The list of tags on a line denes the set of resources whose messages will be included in the
mailing; each additional tag adds to the set, and each !negated tag subtracts from the set.
SSL Conguration: External CA Support
Due to technical diculties, this page cannot be displayed in this PDF le. To view this page on the
web, please see http://docs.puppetlabs.com/puppet/3.6/reference/cong_ssl_external_ca.html.
SSL Conguration: Autosigning Certicate
Requests
CSRs, Certicates, and Autosigning
Before puppet agent nodes can retrieve their conguration catalogs, they need a signed certicate
from the local Puppet certicate authority (CA). When using Puppets built-in CA (that is, not using
an external CA), agents will submit a certicate signing request (CSR) to the CA puppet master and
will retrieve a signed certicate once one is available.
By default, these CSRs must be manually signed by an admin user, using either the puppet cert
Puppet 3.6 Reference Manual SSL Conguration: External CA Support 286/325
command or the node requests page of the Puppet Enterprise console.
Alternately, you can congure the CA puppet master to automatically sign certain CSRs to speed up
the process of bringing new agent nodes into the deployment.
Disabling Autosigning
By default, the CA puppet master will use the $confdir/autosign.conf le as a whitelist; see Basic
Autosigning below. Since this le doesnt exist by default, autosigning is implicitly disabled, and
the CA will not autosign any certicates.
To explicitly disable autosigning, you can set autosign = false in the [master] section of the CA
puppet masters puppet.conf. This will cause the CA to never autosign even if an autosign.conf le
is written later.
Nave Autosigning
Nave autosigning causes the CA to autosign all CSRs.
Enabling Nave Autosigning
To enable nave autosigning, set autosign = true in the [master] section of the CA puppet
masters puppet.conf.
Security Implications of Nave Autosigning
You should never do this in a production deployment. Nave autosigning is only suitable for
temporary test deployments that are incapable of serving catalogs containing sensitive information.
Basic Autosigning (autosign.conf)
In basic autosigning, the CA uses a cong le containing a whitelist of certicate names and
domain name globs. When a CSR arrives, the requested certicate name is checked against the
whitelist le. If the name is present (or covered by one of the domain name globs), the certicate is
autosigned; if not, it is left for manual review.
Enabling Basic Autosigning
To enable basic autosigning, set autosign = <whitelist file> in the [master] section of the CA
puppet masters puppet.conf. The whitelist le must not be executable by the same user as the
puppet master; otherwise it will be treated as a policy executable.
Important security note: Autosigning CSRs will change the nature of your deployments
security, and you should be sure you understand the implications before conguring it. Each
kind of autosigning has its own security impact.
Puppet 3.6 Reference Manual SSL Conguration: External CA Support 287/325
The autosign.conf File
The autosign.conf whitelist le is a list of certnames or domain name globs (one per line) whose
certicate requests will automatically be signed.
rebuilt.example.com
*.scratch.example.com
*.local
Note that domain name globs do not function as normal globs: an asterisk can only represent one
or more subdomains at the front of a certname that resembles a fully-qualied domain name. (That
is, if your certnames dont look like FQDNs, you cant use autosign.conf to full eect.)
Security Implications of Basic Autosigning
Since any host can provide any certname when requesting a certicate, basic autosigning should
only be used in situations where you fully trust any computer able to connect to the puppet master.
With basic autosigning enabled, an attacker able to guess an unused certname allowed by
autosign.conf would be able to obtain a signed agent certicate from the puppet master. They
would then be able to obtain a conguration catalog, which may or may not contain sensitive
information (depending on your deployments Puppet code and node classication).
Policy-Based Autosigning
In policy-based autosigning, the CA will run an external policy executable every time it receives a
CSR. This executable will examine the CSR and tell the CA whether the certicate is approved for
autosigning. If the executable approves, the certicate is autosigned; if not, it is left for manual
review.
Enabling Policy-Based Autosigning
To enable policy-based autosigning, set autosign = <policy executable file> in the [master]
section of the CA puppet masters puppet.conf.
The policy executable le must be executable by the same user as the puppet master. If not, it will
be treated as a certname whitelist le.
Custom Policy Executables
A custom policy executable can be written in any programming language; it just has to be
executable in a *nix-like environment. The puppet master will pass it the certname of the request
Note: Basic autosigning is enabled by default and looks for a whitelist located at
$confdir/autosign.conf. See Conguring Puppetfor details about Puppets confdir.
Puppet 3.6 Reference Manual SSL Conguration: External CA Support 288/325
(as a command line argument) and the PEM-encoded CSR (on stdin), and will expect a 0 (approved)
or non-zero (rejected) exit code.
Once it has the CSR, a policy executable can extract information from it and decide whether to
approve the certicate for autosigning. This is most useful if you are embedding additional
information in the CSR when you provision your nodes.
If you arent embedding additional data, the CSR will contain only the nodes certname and public
key. This can still provide more exibility and security than autosign.conf, as the executable can
do things like query your provisioning system, CMDB, or cloud provider to make sure a node with
that name was recently added.
Security Implications of Policy-Based Autosigning
Policy-based autosigning can be both fast and extremely secure, depending on how you manage
the information the policy executable is using. For example:
If you embed a unique pre-shared key in each node when you provision it, and provide your
policy executable with a database of these keys, your autosigning security will be as good as
your handling of the keys as long as its impractical for an attacker to acquire a PSK, it will be
impractical for them to acquire a signed certicate.
If nodes running on a cloud service embed their instance UUIDs in their CSRs, and your
executable queries the cloud providers API to check that a node with that UUID exists in your
account, your autosigning security will be as good as the security of the cloud providers API. If
an attacker can impersonate a legit user to the API and get a list of node UUIDs, or if they can
create a rogue node in your account, they can acquire a signed certicate.
As you can see, you must think things through carefully when designing your CSR data and signing
policy. As long as you can arrange reasonable end-to-end security for secret data on your nodes,
you should be able to rig up a secure autosigning system.
Policy Executable API
The API for policy executables is as follows:
Run environment: The executable will be run once for each incoming CSR.
It will be executed by the puppet master process and will run as the same user as the puppet
master.
The puppet master process will block until the executable nishes running.We expect policy
executables to nish in a timely fashion; if they do not, its possible for them to tie up all
available puppet master threads and deny service to other agent nodes. If an executable
needs to perform network requests or other potentially expensive operations, the author is in
charge of implementing any necessary timeouts, possibly bailing and exiting non-zero in the
event of failure.
(Note that under a Rack server like Passenger, there are generally multiple puppet master
processes available at any given time, so policy executables have a little bit of leeway.)
Puppet 3.6 Reference Manual SSL Conguration: External CA Support 289/325
Arguments: The executable must allow a single command line argument. This argument will be
the Subject CN (certname) of the incoming CSR.
No other command line arguments should be provided.
The puppet master should never fail to provide this argument.
Stdin: The executable will receive the entirety of the incoming CSR on its stdin stream. The CSR
will be encoded in PEM format.
The stdin stream will contain nothing but the complete CSR.
The puppet master should never fail to provide the CSR on stdin.
Exit status: The executable must exit with a status of 0 if the certicate should be autosigned; it
must exit with a non-zero status if it should not be autosigned.
The puppet master will treat all non-zero exit statuses as equivalent.
Stdout and stderr: Anything the executable emits on stdout or stderr will be copied to the
puppet masters log output at the debug log level. Puppet will otherwise ignore the executables
output; only the exit code is considered signicant.
SSL Conguration: CSR Attributes and
Certicate Extensions
Summary
When puppet agent nodes request their certicates, the certicate signing request (CSR) usually
just contains their certname and the necessary cryptographic information. However, agents can also
embed more data in their CSR. This extra data can be useful for policy-based autosigning. In future
Puppet versions, extensions may also be passed to the compiler as trusted facts.
Status as of Early 2014
In this version of Puppet, embedding additional data into CSRs is mostly useful in deployments
where:
Large numbers of nodes are regularly created and destroyed as part of an elastic scaling system.
You are willing to build custom tooling to make certicate autosigning more secure and useful.
It may also be useful in deployments where:
Puppet is used to deploy private keys or other sensitive information, and you want extra control
over which nodes receive this data.
If your deployment doesnt match one of these descriptions, you may not need this feature.
Puppet 3.6 Reference Manual SSL Conguration: CSR Attributes and Certicate Extensions 290/325
Timing: When Data Can be Added to CSRs / Certicates
When puppet agent starts the process of requesting a catalog, it rst checks whether it has a valid
signed certicate. If it does not, it will generate a key pair, craft a CSR, and submit it to the
certicate authority (CA) puppet master. The steps are covered in more detail in the reference page
about agent/master HTTPS trac.
Once a certicate is signed, it is, for all practical purposes, locked and immutable. Thus, for any
data to persist in the certicate, it has to be added to the CSR before the CA signs the certicate.
This means any desired extra data must be present before puppet agent attempts to request its
catalog for the rst time.
Practically speaking, you should populate any extra data when provisioning the node. If you mess
up, see Recovering From Failed Data Embedding below.
Data Location and Format
Extra data for the CSR is read from the csr_attributes.yaml le in Puppets confdir. (The
location of this le can be changed with the csr_attributes setting.)
The csr_attributes le must be a YAML hash containing one or both of the following keys:
custom_attributes
extension_requests
The value of each key must also be a hash, where:
Each key is a valid object identier (OID) Puppet-specic OIDsmay optionally be referenced by
short name instead of by numeric ID.
Each value is an object that can be cast to a string (that is, numbers are allowed but arrays are
not).
See the respective sections below for information about how each hash is used and recommended
OIDs for each hash.
Custom Attributes (Transient CSR Data)
Custom Attributes are pieces of data that are only embedded into the CSR. They can be used by the
CA when deciding whether or not to sign the certicate, but they are discarded after that and will
Version Note
CSR attributes and certicate extensions are only available in Puppet 3.4 and newer. Access
to extensions in the $trusted hash is available in 3.5 and newer.
Puppet 3.6 Reference Manual SSL Conguration: CSR Attributes and Certicate Extensions 291/325
not be transferred to the nal certicate.
Default Behavior
By default, Puppets CA tools dont do anything with custom attributes. The puppet cert list
command will not display custom attributes for any pending CSRs, and basic autosigning
(autosign.conf) will not check them before signing.
Congurable Behavior
If you are using policy-based autosigning, your policy executable receives the complete CSR in PEM
format. The executable can extract and inspect the custom attributes, and it can use them when
deciding whether to sign the certicate.
The simplest use is to embed a pre-shared key of some kind in the custom attributes. A policy
executable can compare it to a list of known keys and autosign certicates for any pre-authorized
nodes.
A more complex use might be to embed an instance-specic ID, and write a policy executable that
can check it against a list of your recently requested instances on a public cloud like EC2 or GCE.
Manually Checking For Custom Attributes in CSRs
You can check for custom attributes by using OpenSSL to dump a PEM-format CSR to text format.
Do this by running:
$ openssl req -noout -text -in <name>.pem
In the output, look for a section called Attributes, which generally appears below the Subject
Public Key Info block:
Attributes:
challengePassword :342thbjkt82094y0uthhor289jnqthpc2290
Recommended OIDs for Attributes
Custom attributes can use any public or site-specic OID, with the exception of the OIDs used for
core X.509 functionality. This means you cant re-use existing OIDs for things like subject
alternative names.
One useful OID is the challengePassword attribute 1.2.840.113549.1.9.7. This is a rarely-
used corner of X.509 which can easily be repurposed to hold a pre-shared key. The benet of using
this instead of an arbitrary OID is that it will appear by name when using OpenSSL to dump the CSR
to text; OIDs that openssl req cant recognize will be displayed as numerical strings.
You can also use the Puppet-specic OIDs referenced below in the section on extension requests.
Puppet 3.6 Reference Manual SSL Conguration: CSR Attributes and Certicate Extensions 292/325
Extension Requests (Permanent Certicate Data)
Extension requests are pieces of data that will be transferred to the nal certicate(as extensions)
when the CA signs the CSR. They will persist as trusted, immutable data, which cannot be altered
after the certicate has been signed.
They may also be used by the CA when deciding whether or not to sign the certicate.
Default Behavior
When signing a certicate, Puppets CA tools will transfer any extension requests into the nal
certicate.
If trusted facts are enabled, any cert extensions can be accessed in manifests as
$trusted[extensions][<EXTENSION OID>]. Any OIDs in the ppRegCertExt range (see below) will
appear using their short names, and other OIDs will appear as plain dotted numbers. See the page
on facts and special variables for more information about $trusted.
Visibility of extensions is somewhat limited:
The puppet cert list command will not display custom attributes for any pending CSRs, and
basic autosigning (autosign.conf) will not check them before signing. Youll need to either use
policy-based autosigning or inspect CSRs manually with the openssl command (see below).
The puppet cert print command will display any extensions in a signed certicate, under the
X509v3 extensions section.
Puppets authorization system (auth.conf) does not use certicate extensions for anything.
Congurable Behavior
If you are using policy-based autosigning, your policy executable receives the complete CSR in PEM
format. The executable can extract and inspect the extension requests, and it can use them when
deciding whether to sign the certicate.
Manually Checking For Extensions in CSRs and Certicates
You can check for extension requests in a CSR by using OpenSSL to dump a PEM-format CSR to text
format. Do this by running:
$ openssl req -noout -text -in <name>.pem
In the output, look for a section called Requested Extensions, which generally appears below the
Subject Public Key Info and Attributes blocks:
Requested Extensions:
1.3.6.1.4.1.34380.1.1.4:
Puppet 3.6 Reference Manual SSL Conguration: CSR Attributes and Certicate Extensions 293/325
342thbjkt82094y0uthhor289jnqthpc2290
1.3.6.1.4.1.34380.1.1.3:
my_ami_image
1.3.6.1.4.1.34380.1.1.1:
ED803750-E3C7-44F5-BB08-41A04433FE2E
Any Puppet-specic OIDs (see below) will appear as numeric strings when using OpenSSL.
You can check for extensions in a signed certicate by running puppet cert print <name>. In the
output, look for the X509v3 extensions section. Any of the Puppet-specic registered OIDs (see
below) will appear as their descriptive names:
X509v3 extensions:
Netscape Comment:
Puppet Ruby/OpenSSL Internal Certificate
X509v3 Subject Key Identifier:
47:BC:D5:14:33:F2:ED:85:B9:52:FD:A2:EA:E4:CC:00:7F:7F:19:7E
Puppet Node UUID:
ED803750-E3C7-44F5-BB08-41A04433FE2E
X509v3 Extended Key Usage: critical
TLS Web Server Authentication, TLS Web Client Authentication
X509v3 Basic Constraints: critical
CA:FALSE
Puppet Node Preshared Key:
342thbjkt82094y0uthhor289jnqthpc2290
X509v3 Key Usage: critical
Digital Signature, Key Encipherment
Puppet Node Image Name:
my_ami_image
Recommended OIDs for Extensions
Extension request OIDs must be under the ppRegCertExt ( 1.3.6.1.4.1.34380.1.1) or
ppPrivCertExt ( 1.3.6.1.4.1.34380.1.2) OID arcs.
Puppet Labs provides several registered OIDs (under ppRegCertExt) for the most common kinds
of extension information, as well as a private OID range (ppPrivCertExt) for site-specic extension
information. The benets of using the registered OIDs are:
They can be referenced in csr_attributes.yaml using their short names instead of their
numeric IDs.
When using Puppet tools to print certicate info, they will appear using their descriptive names
instead of their numeric IDs.
The private range is available for any information you want to embed into a certicate that isnt
already in wide use elsewhere. It is completely unregulated, and its contents are expected to be
dierent in every Puppet deployment.
PUPPET-SPECIFIC REGISTERED IDS
Puppet 3.6 Reference Manual SSL Conguration: CSR Attributes and Certicate Extensions 294/325
The ppRegCertExt OID range contains the following OIDs:
Numeric ID Short Name Descriptive Name
1.3.6.1.4.1.34380.1.1.1 pp_uuid Puppet Node UUID
1.3.6.1.4.1.34380.1.1.2 pp_instance_id Puppet Node Instance ID
1.3.6.1.4.1.34380.1.1.3 pp_image_name Puppet Node Image Name
1.3.6.1.4.1.34380.1.1.4 pp_preshared_key Puppet Node Preshared Key
AWS Attributes and Extensions Population Example
Generally, you will want to use an automated script (possibly using cloud-init or a similar tool) to
populate the csr_attributes.yaml le at the time a node is provisioned.
As an example, you could enter the following script into the Congure Instance Details >
Advanced Details section when provisioning a new node from the AWS EC2 dashboard:
#!/bin/sh
if [ ! -d /etc/puppet ]; then
mkdir /etc/puppet
fi
erb > /etc/puppet/csr_attributes.yaml <<END
custom_attributes:
1.2.840.113549.1.9.7: mySuperAwesomePassword
extension_requests:
pp_instance_id: <%= %x{/opt/aws/bin/ec2-metadata -i}.sub(/instance-id:
(.*)/,'\1').chomp %>
pp_image_name: <%= %x{/opt/aws/bin/ec2-metadata -a}.sub(/ami-id:
(.*)/,'\1').chomp %>
END
Assuming your image had the erb binary available, this would populate the attributes le with the
AWS instance ID, image name, and a pre-shared key to use with policy-based autosigning.
Troubleshooting
Recovering From Failed Data Embedding
When rst testing this feature, you might fail to embed the right information in a CSR or certicate
and want to start over for your test node(s). (This is not really a problem once your provisioning
system is changed to populate the data, but it can happen pretty easily when doing things
manually.)
In order to start over, youll need to do the following:
On the test node:
Puppet 3.6 Reference Manual SSL Conguration: CSR Attributes and Certicate Extensions 295/325
Turn o puppet agent, if its running.
Check whether a CSR is present; it will be at $ssldir/certificate_requests/<name>.pem. If it
exists, delete it.
Check whether a certicate is present; it will be at $ssldir/certs/<name>.pem. If it exists, delete
it.
On the CA puppet master:
Check whether a signed certicate exists; use puppet cert list --all to see the complete list.
If it exists, revoke and delete it with puppet cert clean <name>.
Check whether a CSR for the node exists; it will be in $ssldir/ca/requests/<name>.pem. If it
exists, delete it.
After youve done that, you can start over.
SSL: Regenerating All Certicates in a Puppet
Deployment
In some cases, you may nd that you need to regenerate the certicates and security credentials
(private and public keys) that are generated by Puppets built-in certicate authority (CA). For
example, you may have a puppet master you need to move to a dierent network in your
infrastructure, or you may nd that you need to regenerate all the certicates and security
credentials in your infrastructure due to an unforeseen security vulnerability.
Note: If youre visiting this page to remediate your Puppet Enterprise deployment due to
CVE-2014-0160, a.k.a. Heartbleed, please see this announcement for additional
information and links to more resources before using this guide. Before applying these
instructions, please bear in mind that this is a non-trivial operation that contains some
manual steps and will require you to replace certicates on every agent node managed by
your puppet master.
IMPORTANT: This page describes the steps for regenerating certs in an open source Puppet
deployment. If you use Puppet Enterprise you should NOT use this page since doing so will
leave you with an incomplete replacement and non-functional deployment. Instead, PE
customers must refer to one of the following pages:
Regenerating certicates in split PE deployments
Regenerating certicates in monolithic PE deployments
Puppet 3.6 Reference Manual SSL: Regenerating All Certicates in a Puppet Deployment 296/325
Regardless of your situation, regenerating your certs involves the following three steps (complete
procedures follow below):
Note that this process destroys the certicate authority and all other certicates.It is meant for use
in the event of a total compromise of your site, or some other unusual circumstance. If you just
need to replace a few agent certicates, you can use the puppet cert clean command on your
puppet master and then follow step 3 for any agents that need to be replaced.
Step 1: Clear and Regenerate Certs on Your Puppet Master
On the puppet master hosting the CA:
1. On your master, youll clear the certs and security credentials, regenerate the CA, and then
regenerate the certs and security credentials.
2. Next, youll clear and regenerate certs and security credentials for any extensions.
3. Lastly, youll clear and regenerate certs and security credentials for all agent nodes.
1. Back up the /etc/puppetlabs/puppet/ssl/ directory. If something goes wrong, you may need
to restore this directory so your deployment can stay functional. However, if you needed to
regenerate your certs for security reasons and couldnt, you should get some assistance as soon
as possible so you can keep your site secure.
2. Stop the puppet agent service with sudo puppet resource service puppet ensure=stopped.
3. Stop the puppet master service. Your puppet master is probably managed by a Rack-supporting
web server, such as Apache with Passenger; youll need to stop that web server. (For example,
sudo puppet resource service apache2 ensure=stopped.)
4. Locate Puppets ssldir by [reading the setting from Puppet][cong_print]; run either sudo puppet
config print ssldir --section master or sudo puppet master --configprint ssldir.
5. Delete all les in the ssldir with sudo rm -rf <PATH TO SSLDIR>.
6. Regenerate the CA by running sudo puppet cert list -a. You should see this message:
Notice: Signed certificate request for ca.
7. Generate the puppet masters new certs with sudo puppet master --no-daemonize --verbose.
8. When you see Notice: Starting Puppet master <your Puppet version>, type CTRL + C.
9. Start the puppet master service by reversing whatever you did in step 3. (E.g., sudo puppet
resource service apache2 ensure=running.)
10. Start the puppet agent service with sudo puppet resource service puppet ensure=running.
At this point:
You have a brand new CA certicate and key.
Your puppet master has a certicate from the new CA, and it can once again eld new
certicate requests.
The puppet master will reject any requests for conguration catalogs from nodes that
havent replaced their certicates (which, at this point, will be all of them except itself).
If you are using any extensions that rely on Puppet certicates, like PuppetDB or Puppet
Puppet 3.6 Reference Manual SSL: Regenerating All Certicates in a Puppet Deployment 297/325
Step 2: Clear and Regenerate Certs for any Extensions
You may be using extensions like PuppetDB or Puppet Dashboard to enhance Puppet. These
extensions probably use certicates from Puppets CA in order to communicate securely with the
puppet master.
For each extension like this, youll need to regenerate the certicate(s) it uses. Many tools have
scripts or documentation to help you set up SSL, and you can often just re-run the setup
instructions.
PuppetDB users should rst follow the instructions below on regenerating agent certicates,
since PuppetDB re-uses puppet agents certicates. After that, run PuppetDBs ssl conguration
script to regenerate its SSL conguration, and restart the PuppetDB service.
Puppet Dashboard can use certicates for its inventory service. Repeat the SSL cong
instructions.
MCollective often uses SSL certicates from Puppets CA. If you are replacing your Puppet CA and
are using the same certs for MCollective, you should go through the standard deployment guide
and re-do any steps involving security credentials. Youll generally need to replace client
certicates, your server keypair, and the ActiveMQ servers keystore and truststore.
Step 3: Clear and Regenerate Certs for Puppet Agents
To replace the certs on agents, youll need to log into each agent node and do the following:
Once an agent nodes new certicate is signed, it will fetch it automatically within a few minutes and
Dashboard, the puppet master wont be able to communicate with them. Consequently, it
may not be able to serve catalogs, even to agents that do have new certicates.
1. Stop the puppet agent service. On *nix nodes, run sudo puppet resource service puppet
ensure=stopped. On Windows nodes, run the same command (minus sudo) with Administrator
privileges.
2. Locate Puppets ssldir and delete everything in it. The ssldir can be located by running puppet
config print ssldir --section agent or puppet agent --configprint ssldir be sure to
run that command with sudo on *nix nodes and with Administrator privileges on Windows
nodes.
3. Re-start the puppet agent service. On *nix nodes, run sudo puppet resource service pe-
puppet ensure=running. On Windows nodes, run the same command (minus sudo) with
Administrator privileges.
Once the puppet agent starts, it will automatically generate keys and request a new certicate
from the CA puppet master.
4. If you are not using autosigning, you will need to sign each agent nodes certicate request. You
can do this by logging into the CA puppet master server, running sudo puppet cert list to
see pending requests, and running sudo puppet cert sign <NAME> to sign requests.
Puppet 3.6 Reference Manual SSL: Regenerating All Certicates in a Puppet Deployment 298/325
begin a Puppet run.
Formats: Reports
Puppet 3.6 uses report format 4.
Report Format 4
This is the format of reports output by Puppet versions 3.3.0 and later. It is backwards-compatible
with report format 3, as it only adds two elds.
Starting with Puppet 3.3.0, report objects being sent to the puppet master can be serialized as pson
(a variant of json that allows byte sequences that arent valid utf-8 characters). This is a change
from Puppet 3.2.4 and earlier, which only allowed reports to be serialized as yaml. The report
serialization format can be changed for compatibility with older puppet masters with the
report_serialization_format setting.
Puppet::Transaction::Report
The Puppet::Transaction::Report contains the following attributes:
name type description
host string the host that generated this report.
time datetime when the run began.
logs array 0 or more Puppet::Util::Log objects.
metrics hash maps from string (metric category) to Puppet::Util::Metric.
resource_statuses hash maps from resource name to Puppet::Resource::Status
conguration_version string or
integer
The "conguration version" of the puppet run. This is a string if the user has specied their own
versioning scheme, otherwise an integer representing seconds since the epoch.
transaction_uuid string A UUID covering the transaction. The query parameters for the catalog retrieval will have
included the same UUID.
report_format integer 4
puppet_version string The version of the Puppet agent.
kind string "inspect" if this report came from a "puppet inspect" run, "apply" if it came from a "puppet apply"
or "puppet agent" run.
status string "failed", "changed", or "unchanged"
Once you have regenerated all agents certicates, everything should now be back to normal
and fully functional under the new CA.
Puppet 3.6 Reference Manual Formats: Reports 299/325
environment string The environment that was used for the puppet run.
Puppet::Util::Log
A Puppet::Util::Log object contains the following attributes:
name type description
le string the pathname of the manifest le which triggered the log message.
line integer the line number in the manifest le which triggered the log message.
level symbol severity of the message. Possible values for level are :debug, :info, :notice, :warning, :err, :alert, :emerg, :crit
message string the message itself.
source string the origin of the log message. This could be a resource, a property of a resource, or the string "Puppet".
tags array each array element is a string.
time datetime when the message was sent.
The file and line attributes are not always present.
Puppet::Util::Metric
A Puppet::Util::Metric object represents all the metrics in a single category. It contains the following
attributes:
name type description
name string name of the metric category. This is the same as the key associated with this metric in the metrics hash of the
Puppet::Transaction::Report.
label string This is the "titleized" version of the name, which means underscores are replaced with spaces and the rst word is
capitalized.
values array All the metric values within this category. Each element is of the form [name, titleized_name, value], where name
is the name of the particular metric as a string, titleized_name is the "titleized" string of the name, and value is
the quantity (an integer or a oat).
The set of particular metrics and categories which appear in a report is a xed set. In a successful
report, the categories and metrics are:
In the time category, there is a metric for every resource type for which there is at least one
resource in the catalog, plus two additional metrics, called config_retrieval and total. Each
value in the time category is a oat.
In the resources category, the metrics are failed, out_of_sync, changed, and total. Each
value in the resources category is an integer.
In the events category, there are up to ve metrics: success, failure, audit, noop, and total.
total is always present; the others are only present when their values are non-zero. Each value
in the events category is an integer.
In the changes category, there is only one metric, called total. Its value is an integer.
Puppet 3.6 Reference Manual Formats: Reports 300/325
Failed reports contain no metrics.
In an inspect report, there is an additional inspect metric in the time category.
Puppet::Resource::Status
A Puppet::Resource::Status object represents the status of a single resource. It contains the
following attributes:
name type description
resource_type string the resource type, capitalized.
title title the resource title.
resource string the resource name, in the form Type[title]. This is always the same as the key corresponding to this
Puppet::Resource::Status object in the resource_statuses hash. *deprecated*
le string the pathname of the manifest le which declared the resource
line integer the line number in the manifest le which declared the resource
evaluation_time oat the amount of time, in seconds, taken to evaluate the resource. Not present in inspect reports.
change_count integer the number of properties which changed. Always 0 in inspect reports.
out_of_sync_count integer the number of properties which were out of sync. Always 0 in inspect reports.
tags array the strings with which the resource is tagged
time datetime the time at which the resource was evaluated
events array the Puppet::Transaction::Event objects for the resource
out_of_sync boolean True if out_of_sync_count > 0, otherwise false. *deprecated*
changed boolean True if change_count > 0, otherwise false. *deprecated*
skipped boolean True if the resource was skipped, otherwise false.
failed boolean True if Puppet experienced an error while evaluating this resource, otherwise false. *deprecated*
containment_path array An array of strings; each element represents a container (type or class) that, together, make up the
path of the resource in the catalog.
Puppet::Transaction::Event
A Puppet::Transaction::Event object represents a single event for a single resource. It contains the
following attributes:
name type description
audited boolean true if this property is being audited, otherwise false. True in inspect reports.
property string the property for which the event occurred. This value will be missing if the provider errored out
before it could be determined.
previous_value string,
array, or
hash
the value of the property before the change (if any) was applied. This value will be missing if the
provider errored out before it could be determined.
Puppet 3.6 Reference Manual Formats: Reports 301/325
desired_value string,
array, or
hash
the value specied in the manifest. Absent in inspect reports. This value will be missing if the
provider errored out before it could be determined.
historical_value string,
array, or
hash
the audited value from a previous run of Puppet, if known. Otherwise nil. Absent in inspect reports.
This value will be missing if the provider errored out before it could be determined.
message string the log message generated by this event
name symbol the name of the event. Absent in inspect reports.
status string one of the following strings: "success", "failure", "noop", "audit", depending on the type of the event
(see below). Always "audit" in inspect reports.
time datetime the time at which the property was evaluated
Puppet::Transaction::Event#status has the following meanings:
success: property was out of sync, and was successfully changed to be in sync.
failure: property was out of sync, and couldnt be changed to be in sync due to an error.
noop: property was out of sync, and wasnt changed due to noop mode.
audit: property was in sync, and was being audited.
Dierences from Report Format 3
Puppet::Transaction::Report gained transaction_uuid.
Puppet::Resource::Status gained containment_path.
Subsystems: Agent/Master HTTPS
Communications
The puppet agent and the puppet master server communicate via HTTPS over host-veried SSL.
The agent/master HTTP interface is REST-like, but varies from strictly RESTful design in several
ways. The endpoints used by the agent are detailed in the HTTP API reference. Note that all HTTP
endpoints are preceded by the environment being used. Note also that access to each individual
endpoint is controlled by auth.conf on the master.
Diagram
This ow diagram illustrates the pattern of agent-side checks and HTTPS requests to the puppet
Note on verication:If the agent does not yet have its own certicate, it will make several
unveried requests before it can switch to veried mode. In these requests, the agent
doesnt identify itself to the master and doesnt check the masters cert against the CA. In the
descriptions below, assume every request is host-veried unless stated otherwise.
Puppet 3.6 Reference Manual Subsystems: Agent/Master HTTPS Communications 302/325
master during a single Puppet run.
See below the image for a textual description of this process, which explains the illustrated steps in
more detail.
Puppet 3.6 Reference Manual Subsystems: Agent/Master HTTPS Communications 303/325
Puppet 3.6 Reference Manual Subsystems: Agent/Master HTTPS Communications 304/325
Puppet 3.6 Reference Manual Subsystems: Agent/Master HTTPS Communications 305/325
Puppet 3.6 Reference Manual Subsystems: Agent/Master HTTPS Communications 306/325
Check for Keys and Certicates
Obtain a Certicate (if necessary)
Note that if the agent has submitted a certicate signing request, an admin user will need to run
puppet cert sign <name> on the CA puppet master before the agent can fetch a signed certicate.
(Unless autosign is enabled.) Since incoming CSRs are unveried, you can use ngerprints to prove
them, by comparing puppet agent --fingerprint on the agent to puppet cert list on the CA
master.
1. Does the agent have a private key at $ssldir/private_keys/<name>.pem?
If no, generate one.
2. Does the agent have a copy of the CA certicate at $ssldir/certs/ca.pem?
If no, fetch it. (Unveried GET request to /certificate/ca. Since the agent is retrieving the
foundation for all future trust over an untrusted link, this could be vulnerable to MITM attacks,
but its also just a convenience; you can make this step unnecessary by distributing the CA
cert as part of your server provisioning process, so that agents never ask for a CA cert over
the network. If you do this, an attacker could temporarily deny Puppet service to brand new
nodes, but would be unable to take control of them with a rogue puppet master.)
3. Does the agent have a signed certicate at $ssldir/certs/<name>.pem?
If yes, skip the following section and continue to request node object.
(If it has a cert but it doesnt match the private key, bail with an error.)
1. Try to fetch an already-signed certicate from the master. (Unveried GET request to
/certificate/<name>.)
If it gets one, skip the rest of this section and continue to request node object.
(If it gets one that doesnt match the private key, bail with an error.)
2. Determine whether the agent has already requested a certicate signing: Look for
$ssldir/certificate_requests/<name>.pem.
If this le exists, the agent will bail, assuming it needs user intervention on the master. If
waitforcert is enabled, it will wait a few seconds and start this section over.
3. Double-check with the master whether the agent has already requested a certicate signing; the
agent may have just lost the local copy of the request. (Unveried GET request to
/certificate_request/<name>.)
If this request doesnt 404, the agent will bail, assuming it needs user intervention on the
master. If waitforcert is enabled, it will wait a few seconds and start this section over.
4. If the agent has reached this step, it has never requested a certicate, so request one now.
(Unveried PUT request to /certificate_request/<name>.)
5. Return to the rst step of this section, in case the master has autosign enabled; if it doesnt, the
Puppet 3.6 Reference Manual Subsystems: Agent/Master HTTPS Communications 307/325
Request Node Object and Switch Environments
Fetch Plugins
If pluginsync is enabled on the agent:
Request Catalog While Submitting Facts
agent will end up bailing at step 2.
1. Do a GET request to /node/<name>.
If successful, read the environment from the node object.
If the node object has one: In all subsequent requests during this run, use this environment
instead of the one in the agents cong le.
If unsuccessful, or if the node object had no environment set, continue using the environment
from the agents cong le.
Note: This step was added in Puppet 3.0.0, to allow an ENC to centrally assign nodes to
environments. The lenient failure mode is because many users auth.conf les didnt allow
access to node objects, since that rule was only added to the default auth.conf in Puppet
2.7.0 and many people dont update their cong les for every upgrade.
1. Do a GET request to /file_metadatas/plugins with recurse=true and links=manage. This is a
special le server mountpoint that scans the lib directory of every module. Note the funky Rails-
esque endpoint pluralization on file_metadata.
2. Check whether any of the discovered plugins need to be downloaded.
If so, do a GET request to /file_content/plugins/<file> for each one.
1. Do a POST request to /catalog/<name>, where the post data is all of the nodes facts encoded as
JSON. Receive a compiled catalog in return.
Note: This used to be a GET request with facts encoded as base64-encoded zlib-compressed
JSON submitted as a URL parameter. This would sometimes cause failures with certain web
servers and a large amount of facts, and was changed to a POST in Puppet 2.7.0. GETs
should still work in Puppet 3 if something other than an agent tries one, but agents will use
POSTs.
Note also that submitting facts isnt necessarily logically bound to requesting a catalog, and
could be done out of band on a dierent schedule; this is just the way Puppet happens to do
it, because the original design assumptions were that relevant facts could change at any
moment and youd always want to guarantee the most recent data. Were experimenting with
other ways, some of which might turn out to be better ideas.
Puppet 3.6 Reference Manual Subsystems: Agent/Master HTTPS Communications 308/325
Make File Source Requests While Applying Catalog
File resources can specify le contents as either a content or source attribute. Content attributes
go into the catalog, and puppet agent needs no additional data. Source attributes only put
references into the catalog, and may require additional HTTPS requests.
If you are using the normal compiler, then for each le source, puppet agent will:
If you are using the static compiler, all le metadata is embedded in the catalog. For each le
source, puppet agent will:
Note that this is cheaper in terms of network trac, but potentially more expensive during catalog
compilation. Large amounts of les, especially recursive directories, will amplify the eect in both
directions.
Submit Report
If report is enabled on the agent:
Subsystems: Catalog Compilation
Background Info
Whats a catalog?
When conguring a node, puppet agent uses a document called a catalog, which it downloads from
1. Do a GET request to /file_metadata/<something>.
2. Compare the metadata to the state of the le on disk.
If it is in sync, move on to the next le source.
If it is out of sync, do a GET request to /file_content/<something> for the current content.
1. Compare the embedded metadata to the state of the le on disk.
If it is in sync, move on to the next le source.
If it is out of sync, do a GET request to /file_bucket_file/md5/<checksum> for the current
content.
1. Do a PUT request to /report/<name>. The content of the PUT should be a Puppet report object
in YAML format.
Note: Yes, using PUT for this is not quite proper, but thats how it was implemented. It may
change in the future.
Puppet 3.6 Reference Manual Subsystems: Catalog Compilation 309/325
a puppet master server. The catalog describes the desired state for each resource that should be
managed, and may specify dependency information for resources that should be managed in a
certain order.
Why is it used?
Puppet manifests are concise because they can express variation between nodes with conditional
logic, templates, and functions. By resolving these on the master and giving the agent just a specic
catalog, Puppet is able to:
Separate privileges: Each individual node has little to no knowledge about other nodes. It only
receives its own resources.
Reduce the agents resource consumption: Since the agent doesnt have to compile, it can use
less CPU and memory.
Simulate changes: Since the agent is just checking resources and not running arbitrary code, it
has the option of simulating changes. If you do a Puppet run in noop mode, the agent will check
against its current state and report on what would have changed without actually making any
changes.
Record and query congurations:If you use PuppetDB, you can query it for information about
managed resources on any node.
What about puppet apply?
Puppet apply compiles its own catalog and then applies it, so it plays the role of both puppet master
and puppet agent.
Information Sources
Puppet compiles a catalog using three main sources of conguration info:
Agent-provided data
External data
Puppet manifests (and associated templates and le sources)
All of these sources are used by both agent/master deployments and by stand-alone puppet apply
nodes.
Agent-Provided Data
When agents request a catalog, they send four pieces of information to the puppet master:
Their name, which is embedded in the request URL. (e.g.
/production/catalog/web01.example.com) This is almost always the same as the certname.
Their certicate,which contains their certname and possibly some extra information. (This is the
one item not used by puppet apply.)
Their facts.
Their requested environment, which is embedded in the request URL. (e.g.
Puppet 3.6 Reference Manual Subsystems: Catalog Compilation 310/325
/production/catalog/web01.example.com) Before requesting a catalog, agents will ask the
master which environment they should be in, but they will use the environment in their own
cong le if the master doesnt have an opinion.
External Data
Puppet can use external data at several stages when compiling, but there are two main kinds to be
aware of:
Data from an ENC or other node terminus, which is available before compilation starts. This data
arrives in the form of a node object, which can contain any of the following:
Classes that should be assigned to the node, and parameters to congure the classes
Extra top-scope variables that should be set for the node
An environment for the node (which will override its requested environment)
Data from other sources, which is accessed as needed during compilation. It may be invoked by
the site manifest or by classes or dened types in modules. This kind of data includes:
Exported resources queried from PuppetDB
The results of functions, which can access arbitrary data sources including Hiera or an
external CMDB
Puppet Manifests, Templates, etc.
This is the heart of a Puppet deployment. It can include:
The site manifest, which might be broken out into per-node .pp les for easier organization
Modules downloaded from the Puppet Forge
Modules written specically for your site
The Process of Catalog Compilation
This description is simplied. It doesnt delve into the internals of the parser, model, evaluator, etc.,
and some items are presented out of order for the sake of conceptual clarity.
For practical purposes, you can treat puppet apply nodes as simply a combined agent and master.
This process begins after the catalog request has been received.
Step 1: Retrieve the Node Object
Once the puppet master has the agent-provided information for this request, it asks its congured
node terminus for a node object.
By default, puppet master uses the plain node terminus, which just returns a blank node object.
This results in only manifests and agent-provided info being used in compilation.
The next most common node terminus is the exec node terminus, which will request data from an
external node classier (ENC). This may return classes, variables, and/or an environment,
Puppet 3.6 Reference Manual Subsystems: Catalog Compilation 311/325
depending on how the ENC is designed.
Less commonly, some people use the ldap node terminus, which will fetch ENC-like information
from an LDAP database. See the page on LDAP nodes for more information.
Finally, its possible to write a custom node terminus that retrieves classes, variables, and
environments from any kind of external system.
Step 2: Set Variables from the Node Object, from Facts, and from the Certicate
Any variables provided by the node object will now be set as top-scope Puppet variables.
The nodes facts are also set as top-scope variables.
If you have set trusted_node_data = true in the masters puppet.conf, then facts will also be
set in the protected $facts hash, and certain data from the nodes certicate will be set in the
protected $trusted hash. See the page on facts and built-in variables for more details.
All of these variables will be available for use by any manifest or template during the subsequent
stages of compilation.
Step 3: Evaluate the Site Manifest
Puppet now parses the site manifest. The nodes environment may specify a site manifest to use; if
it doesnt, the puppet master will use the main site manifest from its cong le.
The site manifest can contain any arbitrary Puppet code. The way it is evaluated is:
If there are any node denitionsin the manifest, Puppet must nd one that matches the nodes
name (see agent-provided information, above). See the page on node denitionsfor information
on how node statements match names.
If at least one node denition is present and Puppet cannot nd a match, it will fail
compilation now.
Any code outside any node denition is evaluated. Any resources are added to the nodes
catalog. Any class declarations cause classes to be loaded from modules and declared (see Step
3a below).
If a matching node denition was found, any code in it is evaluated at node scope. (This means it
may contain variable assignments that can override top-scope variables.) Any resources are
added to the catalog, and any class declarations cause classes to be loaded and declared.
Step 3a: Load and Evaluate Classes from Modules
Its possible for the site manifest to contain class denitions, but usually classes are dened
elsewhere, in modules.
If any classes were declared in the site manifest and their denitions were not present, Puppet will
automatically load the manifests containing them from its collection of modules. It will follow the
normal manifest naming conventions to locate the les it should load.
Puppet 3.6 Reference Manual Subsystems: Catalog Compilation 312/325
Once a class is loaded, the Puppet code in it is evaluated, and any resources are added to the
catalog. If it was declared at node scope, it has access to any node-scope variables; otherwise, it
only has access to top-scope variables.
Classes can also declare other classes; if they do, Puppet will load and evaluate those in the same
way.
Step 4: Evaluate Classes from the Node Object
Finally, after Puppet has evaluated the site manifest and any classes it declared (and any classes
they declared), it will load from modules and evaluate any classes that were specied by the node
object. Resources from those classes will be added to the catalog.
If a matching node denition was found in step 3, these classes are evaluated at node scope, which
means they can access any node-scope variables set by the site manifest. If no node denitions
were present in the site manifest, they will be evaluated at top scope.
Experimental Features: Overview
Summary
Starting in the Puppet 3.x series, ocially released versions of Puppet may include certain
experimental features, which are turned o by default. See the sidebar menu of this page for
information on the experimental features currently available.
Typically, these features are being considered for widespread adoption but are not yet ready for
production. Sometimes they have a solid design but unknown performance and resource usage and
need to be tested in the eld before they can be considered safe. Other times, even the design is
tentative, and we need feedback from users who nd it usable or unusable.
By shipping these features early in disabled form, we hope to lower the bar for testing and giving
feedback. We want it to be easier for normal users to join conversations about Puppets future.
Risks and Support
Experimental features are not ocially supportedby Puppet Labs, and we do not recommend that
you turn them on in a production environment. They are available for testing in relatively safe
scratch environments, and are used at your own risk. Puppet employees and community members
will do their best to help you in informal channels like IRC and the puppet-users and puppet-dev
mailing lists, but we make no promises about experimental functionality.
Enabling experimental features may degrade the performance of your Puppet infrastructure,
interfere with the normal operation of your managed nodes, introduce unexpected security risks,
or have other undesired eects.
Puppet 3.6 Reference Manual Experimental Features: Overview 313/325
This is especially relevant to Puppet Enterprise customers. If Puppet Labs support is assisting you
with a problem, we may ask you to disable any experimental features.
Changes to Experimental Features
Experimental features are exempt from semantic versioning they may change at any time, not
limited to major or minor release boundaries.
These changes may include adding or removing functionality, changing the names of settings and
other aordances, and more.
Documentation of Experimental Features
The Puppet reference manual contains documentation pages for all of the currently available
experimental features. These pages will be focused on enabling a feature and running through the
most interesting parts of its functionality; they may lag slightly behind the feature as implemented.
When a feature has experienced major changes across minor versions, we will note the dierences
at the top of that features page.
Each features page will attempt to give some context about the status of that feature and its
prospects for ocial release.
Giving Feedback on Experimental Features
If you are testing Puppets experimental features: Thank you! Please tell us more about your
experience, so we can keep making Puppet better.
The best places to talk about experimental features are the puppet-users and puppet-dev
mailing lists. This tells us whats working and what isnt, while also helping others learn from
your experience. For more information about the Puppet Labs mailing lists, please see the
community guidelines for mailing lists.
For more immediate conversations, you can use the #puppet and #puppet-dev channels on
irc.freenode.net. For more information about these channels, please see the community
guidelines for IRC.
Experimental Features: The Future Parser
Warning: This document describes an experimental feature, which is not ocially supported
and is not considered ready for production. See here for more information about
experimental features in Puppet, especially if you are using Puppet Enterprise.
Status: In Puppet 3.6, the future parser performs much better than it used to. We think its
Puppet 3.6 Reference Manual Experimental Features: The Future Parser 314/325
You can set parser = future in puppet.conf to enable experimental new language features, which
may or may not be included in a future Puppet version.
Under the hood, the future parser is a ground-up reimplementation of the Puppet grammar and
evaluator. In addition to the experimental features it includes, the future parser makes some
other changes and clean-ups to the language.
Enabling the Future Parser
To enable the future parser:
On your puppet master(s) (or all nodes, if running puppet apply), ensure the rgen gem is
installed. If you installed Puppet from the ocial packages, this was already installed as a
dependency; otherwise, you may need to install it manually.
On your puppet master(s) (or each node, if running puppet apply), set parser = future in the
[master] or [main] section of puppet.conf. (In a masterless puppet apply deployment, use
[main].)
Alternately, for one-o tests, you can set --parser future on the command line when
running puppet apply.
Toggling the Future Evaluator
By default, the future parser also uses a new evaluator. (The parser is what turns the source text
into a model; the evaluator is what takes actions based on the model for example, reducing a
complex expression into a simpler expression, or adding a resource to the catalog based on a
resource declaration.)
The new evaluator defaults to enabled when the future parser is turned on, but it can be
independently deactivated by setting evaluator = current in puppet.conf or --evaluator
current on the command line.
This is generally only useful if youre comparing the old and new compilation systems and need to
track down dierences in catalog output.
Lambdas and Iteration
about on par with the default parser, but havent extensively speed tested it with real-world
manifests. It should still be considered a preview, but can now be used with larger test
environments.
The new language features in the future parser are still being designed and considered. If
you want to join the conversation, or if some of your manifests dont work the way you think
they should under the future parser, please join the puppet-users group and tell us what
youve learned.
Puppet 3.6 Reference Manual Experimental Features: The Future Parser 315/325
The most complex features added by the future parser involve iterations and transformations
acting on collections of data.
These features are covered in a separate document:
Experimental Features: Lambdas and Iteration
Other New Language Features
The future parser makes several other additions to the Puppet language.
Expressions Are Now Valid Statements
In Puppet 3 it is not possible to have a body of code that is just an expression. This makes it
dicult to enter predicates as in the case of a collect or reject.
An expression such as
1 + 2
is now a legal statement if it appears as the last statement in a block. Block return their last
expression/statement as its produced result. There is no explicit return, it is always the value of
the last evaluated expression.
Array/Hash Literals are Now Allowed Anywhere Arrays/Hashes are Allowed
In Puppet 3, if you wanted to operate on a literal array or hash, you typically had to assign it to a
variable rst. This was due to how the internal grammar for the language was organized. You can
now use literal arrays and hashes more naturally in a puppet manifest.
notice([1, 2][1])
# produces the output
Notice: Scope(Class[main]): 2
Concatenation and Append
You can concatenate array and merge hashes with +
[1,2,3] + [4,5,6] # produces [1,2,3,4,5,6]
{a => 1} + {b => 2} # produces {a=>1, b=>2 }
You can append to an array with <<
[1,2,3] << 10 # produces [1,2,3,10]
[1,2,3] << [4,5] # produces [1,2,3,[4,5]]
Puppet 3.6 Reference Manual Experimental Features: The Future Parser 316/325
A Semicolon Acts as an Optional Expression Separator
There is one corner case in the expression based grammar that required an expression separator ;
to be added. It can optionally be used to increase readability in one-liners.
$a = 1; $b = 10
Which naturally also is legal without the semicolon.
The separator becomes important when you want to end a block with a literal array or hash, and
when they would alter the meaning of the preceding operand. (This example makes use of + to
concatenate two arrays)
{ $x = [[1],[2],[3]]
$a = [a] + $x[1]
}
# Results in $a being assigned [a,2], and this is also the value
# returned by the block
is very dierent from:
{ $x = [[1],[2],[3]]
$a = [a] + $x; [1]
}
# Results in $a being assigned to [a, [1],[2],[3]] and the
# result of the block (which is returned) is [1]
Functions That Produce a Value May Be Invoked as Statements
It is harmless to call a function that produce a value and not use the returned value. Puppet 3
forbids this and raises an error. With the entry of iteration functions (which always return a value,
but may be used for only the side eects) this was made impossible by Puppet 3s separation of
function (returning a value) and procedure (returning nothing).
Right Side of Matches May Be a String (unnished)
It is allowed to have a string instead of a regular expression in matches expressions. The intent is
to support variable interpolation in these strings before they are converted to regular expressions.
This is unnished, and will currently result in an error when evaluated (instead of when parsed).
Unless with Else Supported
An unless can now have an else clause (but it cannot be combined with an elsif).
While not being recommended to use complex logic in unless, it is at the same time quite annoying
to have to reverse tests in order to be able to do something like a notice unless not triggered for
Puppet 3.6 Reference Manual Experimental Features: The Future Parser 317/325
debugging.
Chained Assignments
Chained assignments are now possible for both =, and +=.
$a = $b = 10
Note that = and += have low precedence, so this is an error:
$a = 1 + $b = 10 # i.e. this is parsed as $a = (1 + $b) = 10
and needs to be written
$a = 1 + ($b = 10)
Assignments may thus also be used where expressions are.
Function Calls in Interpolation Supported
Calling a function in interpolation now works:
notice "This is a random number: ${fqdn_rand(30)}
This has mysterious result in the regular parser since it is interpreted as
${$fqdn_rand(30)}
New Language Restrictions
Since the future parser will not be enabled until at least the next major version boundary, we took
the opportunity to clean up certain edge cases and oddities in the language. Most code written for
the current parser should be forward compatible, but watch for these changes:
User Dened Numeric Variables Not Allowed
Assignments to numeric variables are agged as errors.
This is illegal:
$3 = 'hello'
In some puppet versions this produces strange eects, and in some it is silently ignored.
Puppet 3.6 Reference Manual Experimental Features: The Future Parser 318/325
As a consequence it is also illegal to name parameters in denes, and parameterized classes with
numeric names.
This is illegal:
define mytype ($1, $2) { }
It is ok to use names with digits 0-9 as long as one character is not a digit.
Capitalized Variable Names Not Allowed
Variable names may not contain capital letters. They are limited to lowercase letters, numbers, and
underscores.
Bare Words May Not Start with a Digit
The positive eect of this is that numbers entered without quotes can be validated to be correct
decimal, hex or octal values.
Numbers Are Validated If Entered without Quotes
If you enter an unquoted number in decimal, hex or octal it is now validated, and an error is raised
if it is illegal.
These will raise errors:
$a = 0x0EH
$b = 0778
Error Reporting Improvements
Another feature of the future parser is that its now possible to introspect extra information about
errors. We use this to improve error messages when using it.
Many Errors Now Contain Position on Line
If available, errors now output position on the line. This helps for errors related to punctuation
such as { since it may appear several times on a line and the problem may be hard to
nd/understand. (This problem was made worse with the addition of lambdas to the language
since they are typically entered as one-liners).
The output format is: filename:line:pos
Pos is never displayed without a line; if you see file:3, it is a reference to the line.
Position starts from 1 (rst character on a line is in position 1).
Puppet 3.6 Reference Manual Experimental Features: The Future Parser 319/325
Odd Expected Errors Fixed
When there is a syntax error involving a token that is paired (e.g. {, (, [), the error message always
said expected ... and it showed the matching side of the violating token. This is only correct if
the problem is reaching EOF. In all other cases this information was misleading, and adding what
was suggested would almost always make things worse.
The expected is now only included when encountering the end of le and there are outstanding
expectations (such as terminating an open string).
Error and Warning Feedback
Error and Warning feedback from parsing now outputs multiple errors / warnings (if multiple were
found before lower level parsing gave up). The default cap on output of these are 10. The number
can be changed via the following puppet.conf settings:
max_errors
max_warnings
max_deprecations
When there are multiple errors, the output emits errors up to the cap. A nal error is then
generated with the error and warning count. If there is only one error, only this error is emitted (no
count). Deprecations count as warnings.
As an example, you can try this:
$ puppet apply --parser future -e '$a = node "a+b" { }'
Error: Invalid use of expression. A Node Definition does not produce a value at
line 1:6
Error: The hostname 'a+b' contains illegal characters (only letters, digits,
'_', '-', and '.' are allowed) at line 1:11
Error: Classes, definitions, and nodes may only appear at toplevel or inside
other classes at line 1:6
Error: Could not parse for environment production: Found 3 errors. Giving up on
node henriks-macbook-pro.local
Fat Arrow (=>) as Comma Is Not Supported
In the Puppet 3 parser, it is allowed to use a fat arrow => in many places where a comma is
required. This undocumented feature is removed in the experimental parser.
Experimental Features: Lambdas and
Iteration
Puppet 3.6 Reference Manual Experimental Features: Lambdas and Iteration 320/325
Lambdas and iteration are an experimental addition to the language, included in the also-
experimental future parser. They can allow you to quickly create groups of resources based on
data, as well as manipulate data in other ways.
This page is user-oriented (in contrast to the technical background information found in ARM-
2.Iteration), and oers an introduction to iteration in Puppet and lambdas.
For a demonstration with context, see this revision of the puppet-network module. (See also the
GitHub home for the revised module.)
Enabling Lambdas and Iteration
You must enable the future parser to use any of the features on this page. See the Enabling the
Future Parser section of the future parser page for details.
Lambdas
A Lambda can be thought of as parameterized code blocks; a block of code that has parameters
and can be invoked/called with arguments. A single lambda can be passed to a function (such as
the iteration function each).
$a = [1,2,3]
each($a) |$value| { notice $value }
We can try this on the command line:
puppet apply --parser future -e '$a=[1,2,3] each($a) |$value|{ notice $value }'
Notice: Scope(Class[main]): 1
Notice: Scope(Class[main]): 2
Notice: Scope(Class[main]): 3
Notice: Finished catalog run in 0.12 seconds
Warning: This document describes an experimental feature, which is not ocially supported
and is not considered ready for production. See here for more information about
experimental features in Puppet, especially if you are using Puppet Enterprise.
Status: In Puppet 3.6, the future parser performs much better than it used to. We think its
about on par with the default parser, but havent extensively speed tested it with real-world
manifests. It should still be considered a preview, but can now be used with larger test
environments.
The new language features in the future parser are still being designed and considered, and
there is ongoing debate over how they should work and whether they should be an ocial
part of Puppet.
Puppet 3.6 Reference Manual Experimental Features: Lambdas and Iteration 321/325
Lets look at what we just did:
We used puppet apply and passed the --parser future option to get the experimental parser,
as described above. (All examples below assume this is set in puppet.conf).
We called a function called each
We passed an array to it as an argument
After the list of arguments we gave it a lambda:
The lambdas parameters are declared within pipes ( |) (just like parameters are specied for a
dene).
We declared the lambda to have one parameter, and we named it $value (we could have
called it whatever we wanted; $x, or $a_unicorn, etc.)
The lambdas body is enclosed in braces { }, where you can place any puppet logic except
class, dene, or node statements.
Available Functions
You have already seen the iteration function each (there is more to say about it), but before going
into details, meet the entire family of iteration functions.
each iterates over each element of an array or hash
map transforms an array or a hash into a new Array
filter lters an array or hash (include elements for which lambda returns true)
reduce reduces an array or hash to a single value which is computed by the lambda
slice slices an array or hash into chunks and feeds each result to a lambda
The function each calls a lambda with one or two arguments (depending on how many are used in
the lambda parameters).
For an array:
If one parameter is used, it will be set to the value of each element. If two parameters are used, they
will be set to the index and value of each element.
For a hash:
If two parameters are used, they will be set to the key and value of each hash entry. If one
parameter is used, it is set to an array containing [key, value].
Using a similar example as before, but now with two parameters, we get:
user$ puppet apply -e '$a = ['a','b','c'] each($a) |$index, $value| { notice
"$index = $value" }'
Puppet 3.6 Reference Manual Experimental Features: Lambdas and Iteration 322/325
Notice: Scope(Class[main]): 0 = a
Notice: Scope(Class[main]): 1 = b
Notice: Scope(Class[main]): 2 = c
The remaining functions also operate on arrays and hashes, and always convert hash entries to an
array of [key, value].
Here are some examples to illustrate:
filter([1,20,3]) |$value| { $value < 10 }
# produces [1,3]
reduce([1,2,3]) |$result, $value| { $result + $value }
# produces: 6
slice(['fred', 10, 'mary', 20], 2) |$name, $val| { notice "$name = $val" }
# results in the following output
Notice: Scope(Class[main]): fred = 10
Notice: Scope(Class[main]): mary = 20
Chaining Functions
You can chain function calls from left to right. And a chain may be as short as a single step.
The examples you have seen can be written like this:
[1,2,3].each |$index, $value| { notice "$index = $value" }'
[1,20,3].filter |$value| { $value < 10 }
[1,2,3].reduce |$result, $value| { $result + $value }
['fred', 10, 'mary', 20].slice(2) |$name, $val| { notice "$name = $val" }
And then lets chain these:
[1,20,3].filter |$value| {$value < 10 }.each |$value| { notice $value }
# produces the output
Notice: Scope(Class[main]): 1
Notice: Scope(Class[main]): 3
Note: It is possible to chain functions that produce a value (which includes the iteration functions,
but not functions like notice).
Learning More About the Iteration Functions
The functions are documented as all other functions and this documentation is available in arm-
Puppet 3.6 Reference Manual Experimental Features: Lambdas and Iteration 323/325
2.iteration Functions for iteration and transformation.
Here is the Index of arm-2 if you want to read all the details, alternatives, and what has been
considered so far.
Lambda Scope
When a lambda is evaluated, this takes place in a local scope that shadows outer scopes. Each
invocation of a lambda sets up a fresh local scope. The variables assigned (and the lambda
parameters) are immutable once assigned, and they can not be referenced from code outside of the
lambda block. The lambda block may however use variables visible in the scope where the lambda
is given, as in this example:
$names = [fred, mary]
[1,2].each |$x| { notice "$i is called ${names[$x]}"}
Calls with Lambdas
You can place a lambda after calls on these forms:
each($x) |$value| { }
$x.each |$value| { }
$x.each() |$value| { }
slice($x, 2) |$value| { }
$x.slice(2) |$value| { }
But these are illegal:
each $x |$value| { }
slice $x, 2 |$value| { }
$z = |$value| { }
Statements in a Lambda Body
The statements in a lambda body can be anything legal in Puppet except denition of classes,
resource types (i.e. dene), or nodes. This is the same rule as for any conditional construct in
Puppet.
Experimental Features: Msgpack Support
Warning: This document describes an experimental feature, which is not ocially supported
Puppet 3.6 Reference Manual Experimental Features: Msgpack Support 324/325
Background on Msgpack
Puppet agents and masters communicate over HTTPS, exchanging structured data in some
serialization format. Traditionally, this has been a mix of YAML and JSON (or actually PSON, which
allows binary data); more recently, weve been trying to deprecate YAML and move entirely to PSON.
Msgpack is an ecient (in space and time) serialization protocol that behaves similarly to JSON. It
should provide faster and more robust serialization for agent/master communications, without
requiring many changes in our code.
When msgpack is enabled, the puppet master and agent will communicate using msgpack instead
of PSON or YAML.
Enabling Msgpack Serialization
Enabling msgpack is easy, but enabling it requires a change on both the master and all agent
nodes.
Once this is congured, the puppet master server(s) will use msgpack when serving any agents that
have preferred_serialization_format set to msgpack. Any agents without that setting will
continue to receive PSON as normal.
2010 Puppet Labs [email protected] 411 NW Park Street / Portland, OR 97209 1-877-575-
9775
and is not considered ready for production. See here for more information about
experimental features in Puppet, especially if you are using Puppet Enterprise.
Status: We think Msgpack is probably superior to our existing serialization formats, but we
arent sure yet and havent tested all edge cases. If it proves to do well under real-world
loads, we may eventually adopt it as our default wire format.
1. Install the msgpack gem on your master and all agent nodes.
If you are using a Puppet Enterprise test environment, be sure to use PEs gem command
instead of the system gem command. On *nix nodes, use /opt/puppet/bin/gem install
msgpack. On Windows 32-bit systems, use "C:\Program Files\Puppet
Labs\Puppet\sys\ruby\bin\gem" install msgpack; on 64-bit systems, substitute Program
Files (x86) for Program Files.
2. On any number of agent nodes, set the preferred_serialization_format setting to msgpack
(in the [agent] or [main] section of puppet.conf).
Puppet 3.6 Reference Manual Experimental Features: Msgpack Support 325/325

You might also like