Sysadmin
Sysadmin
Sysadmin
System
Administration
Using Puppet
Certification
Contents
Definitions 1
Introduction 1
Introduction to Puppet 1
Nodes 1
Installing Puppet 1
pe.conf 2
Installation Directories 2
Puppet Ports 3
puppet.conf 4
Commands 8
Facter 8
Regenerating Certificates 9
Autosigning 9
Module Directories 10
Autoloading 11
Example 11
Custom Facts 11
External Facts 12
DSL Overview 13
Resource Types 13
Style Guide 13
Quoting 15
Module Metadata 15
Resources 16
Parameter 18
Class Inheritance 18
Variables 19
Conditionals 20
Data Types 20
Relationship Metaparameters 22
Chaining Arrows 22
Ordering 23
Missing Dependencies 24
Failed Dependencies 24
Dependency Cycles 24
Conditional Statements 24
"If" Statements 24
"Unless" statements 26
Case Statements 26
Selectors 28
Variable Interpolation 30
Scope 31
Metaparameters 32
params.pp 34
Puppet Functions 35
Functions 35
Templates 36
Resource Collectors 38
Operators 39
Exported Resources 39
Purpose 39
NTP Module 40
Exported Resources 41
Overview 41
Profiles 42
Roles 42
Hiera Overview 43
Setting Up Hiera 44
Overview 45
Nginx Module 48
Node Classification 49
Example: 50
Overview 50
Orchestrator Workflow 51
MCollective Overview 51
Overview 51
Using MCollective 52
Using sudo 52
Host Filters 53
Troubleshooting 53
Troubleshooting Connections 54
General Troubleshooting 55
Database Troubleshooting 55
Reporting 56
Removing Nodes 57
Definitions
Component modules: Normal modules that manage one particular technology. (For example,
puppetlabs/apache.)
Idempotence: The property of certain operations in mathematics and computer science, that
can be applied multiple times with changing the result beyond the initial application. Catalog can be applied
multiple times without causing issue.
Profiles: Wrapper classes that use multiple component modules to configure a layered technology
stack.
Roles: Wrapper classes that use multiple profiles to build a complete system configuration.
Introduction
Introduction to Puppet
Puppet Head First
Install the Puppet Master: ./puppet-enterprise-installer
Nodes
Supported Operating Systems
Installing Puppet
Install the Puppet Master: ./puppet-enterprise-installer
-1-
System Administration Using Puppet Certification Linux Academy
-h - Display help
-q - Run in quiet mode; the installation process is not displayed. Requires answer file.
pe.conf
The pe.conf file is a HOCON-formatted file that declares parameters and values needed to install and
configure Puppet Enterprise.
Found in /etc/puppetlabs/enterprise/conf.d.
{
"console_admin_password": "password",
"puppet_enterprise::puppet_master_host": "<puppet-master-fqdn>",
"pe_install::puppet_master_dnsaltnames": [
"puppet"
]
}
Installation Directories
Puppet Enterprise configuration files are installed in /etc/puppetlabs/puppet for *nix nodes
and <COMMON_APPDATA>\PuppetLabs for Windows nodes.
Environments: /etc/puppetlabs/code/environments
-2-
System Administration Using Puppet Certification Linux Academy
manifests: Contains the main starting point for catalog compilation (applies to master only)
Puppet Ports
3000: Used for the web-based installer of the Puppet Master.
8140: The port that the Puppet Master and agent communicate on.
443: The web port used to access the Puppet Enterprise Console.
5432: PostgreSQL runs on this port. It is used by PuppetDB in a split stack configuration.
8142: Used by Orchestration services to accept inbound traffic/responses from the Puppet agents.
pe-activemq: The ActiveMQ message server, which passes messages to the MCollective servers
on agent nodes. Runs on servers with the Puppet master component.
pe-puppetserver: The Puppet master server, which manages the Puppet master component.
-3-
System Administration Using Puppet Certification Linux Academy
mcollective: The MCollective daemon, which listens for messages and invokes actions. Runs on
every agent node.
puppet (on EL and Debian-based platforms): The Puppet agent daemon. Runs on every agent
node.
pe-puppetdb and pe-postgresql: Daemons that manage and serve the database components.
Note that pe-postgresql is only created if we install and manage PostgreSQL for you.
puppet.conf
The puppet.conf file is located in /etc/puppetlabs/puppet.
Config 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.
-4-
System Administration Using Puppet Certification Linux Academy
Note: Settings are loaded at service start time, to apply changes made to puppet.conf a restart to the pe-
puppet service is required.
Interpolating variables
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, prefix its name with a dollar
sign.
Example:
$codedir
$confdir
$vardir
[main]
certname = master.vagrant.vm
server = master.vagrant.vm
user = pe-puppet
group = pe-puppet
environment_timeout = 0
app_management = true
module_groups = base+pe_only
environmentpath = /etc/puppetlabs/code/environments
codedir = /etc/puppetlabs/code
[agent]
graph = true
[master]
node_terminus = classifier
storeconfigs = true
storeconfigs_backend = puppetdb
reports = puppetdb
certname = master.vagrant.vm
always_cache_features = true
[main]
server = master.vagrant.vm
certname = agent1.vagrant.vm
Basic settings
always_retry_plugins: Affects how we cache attempts to load Puppet resource types and
features.
basemodulepath: The search path for global modules. Should be specified as a list of
-5-
System Administration Using Puppet Certification Linux Academy
Default: $codedir/modules:/opt/puppetlabs/puppet/modules
dns_alt_names: A list of hostnames the server is allowed to use when acting as the Puppet
master. The hostname that an agent uses must be included this list or the agent will fail connecting
to master. The hostname can also live in the certname setting.
manifest: The entry-point manifest for puppet master. This can be one file 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 .
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, log, store.)
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.
store: Store the YAML report on disk. Each host sends its report as a YAML dump and this
just stores the file on disk, in the reportdir directory.
Default: store
server: The Puppet master server to which the Puppet agent should connect.
ignoreschedules: Schedules allow you to only execute a resource if it's during a specific
time period; this setting can disable that feature that might be used when you are doing an initial
setup on a node and everything needs to be executed or enforced the first time around
noop: Agent will not do any work only simulate changes and report to the master.
priority: The scheduling priority of the process. Valid values are 'high', 'normal', 'low', or
'idle', which are mapped to platform-specific values.
tags: Limit the Puppet run to include only resources with certain tags (cool), specific data
centers, etc
waitforcert: Keep trying to run puppet agent if the certificate is not initially available (gives
time for the master to sign)
Resource Type:
Every resource is managed by aresource type
atitle
a set ofattributes.
<TYPE> { '<TITLE>':
<ATTRIBUTE> => <VALUE>,
}
Example
user { 'username':
ensure => present,
uid => '102',
gid => 'wheel',
shell => '/bin/bash',
home => '/home/username',
managehome => '',
}
-7-
System Administration Using Puppet Certification Linux Academy
Commands
puppet describe will provide information about resource types within Puppet
puppet resource will describe information about resources already installed on a running node
puppet agent will send a report to the Puppet master with all facts and information about the
node, this is the node object
puppet agent will ensure that the agent's private key file is present
Facter
facter: Returns a list all facts.
Command:
puppet cert
puppet cert list
puppet cert sign <NAME>
puppet cert revoke <NAME>
DNS altnames:
puppet cert sign (<HOSTNAME> or --all) --allow-dns-alt-names <NAME>
-8-
System Administration Using Puppet Certification Linux Academy
Regenerating Certificates
On the Puppet Master
puppet cert clean<NAME>
Autosigning
Should only be used when the environment can fully trust any computer able to connect to the
Puppet master.
The CA uses a config file containing a whitelist of certificate names and domain names.
$confdir/autosign.conf
.domain.com
Lowercase letters
Digits
Underscores
\A[a-z][a-z0-9_]*\Z
\A([a-z][a-z0-9_]*)?(::[a-z][a-z0-9_]*)*\Z
Class Syntax:
class <CLASS_NAME> (
-9-
System Administration Using Puppet Certification Linux Academy
<DATA_TYPE> <PARAM_NAME>
) {
puppet code ...
}
Example:
class ssh {
file { "/etc/ssh/ssh_config":
ensure => file,
source => "puppet:///modules/ssh/ssh_config"
}
}
Lowercase letters
Numbers
Underscores
<MODULE NAME>
manifests
files
templates
lib
facts.d
examples
spec
functions
types
Module Directories
manifests/ Contains all of the manifests in the module.
lib/ Contains plugins, like custom facts and custom resource types.
facts.d/ Contains external facts, which are an alternative to Ruby-based custom facts.
- 10 -
System Administration Using Puppet Certification Linux Academy
examples/ Contains examples showing how to declare the module's classes and defined types.
spec/ Contains spec tests for any plugins in the lib directory.
Autoloading
Names map to the file
Any segments between the first and last are subdirectories in the manifests directory.
Example
apache - <MODULE DIRECTORY>/apache/manifests/init.pp
apache::mod - <MODULE DIRECTORY>/apache/manifests/mod.pp
apache::mod::passenger - <MODULE DIRECTORY>/apache/manifests/mod/
passenger.pp
Usually shell commands are issued as part of the fact to return information.
Executed on the Puppet nodes with the External Facts Plugin Module.
Example:
# hardware_platform.rb
Facter.add('hardware_platform') do
setcode do
Facter::Core::Execution.exc('/bin/uname --hardware-platform')
end
- 11 -
System Administration Using Puppet Certification Linux Academy
end
External Facts
External facts provide a way to use arbitrary executables or scripts as facts, or set facts statically with
structured data.
In a Module:
<MODULEPATH>/<MODULE>/facts.d/
On Unix/Linux/OS X:
/opt/puppetlabs/facter/facts.d/
/etc/puppetlabs/facter/facts.d/
/etc/facter/facts.d/
On Windows:
C:\ProgramData\PuppetLabs\facter\facts.d\
On Windows 2003:
C:\Documents and Settings\All Users\Application Data\PuppetLabs\facter\
facts.d\
- 12 -
System Administration Using Puppet Certification Linux Academy
DSL Overview
Resource Types
Resource types are the basic building blocks of the Puppet DSL.
atitle
a set ofattributes
<TYPE> { '<TITLE>':
<ATTRIBUTE> => <VALUE>,
}
ensure:
Attributes:
source
content
target
Review all the resource types by visiting the Resource Type Reference
Style Guide
The style guide is to promote consistent formatting in the Puppet Language, especially across
modules, giving users and developers of Puppet modules a common pattern, design, and style to follow.
Readability matters.
- 13 -
System Administration Using Puppet Certification Linux Academy
Must include trailing commas after all resource attributes and parameter definitions,
Must use one space between the resource type and opening brace, one space between the
opening brace and the title, and no spaces between the title and colon.
Module manifests:
Should not exceed a 140-character line width, except where such a limit would be impractical
Should leave one empty line between resources, except when using dependency chains
May align hash rockets (=>) within blocks of attributes, one space after the longest resource
key, arranging hashes for maximum readability first.
Example:
file { '/tmp/foo': }
First and last lines used only for the syntax of that data type
Example
# array with multiple elements on multiple lines
service { 'some_service':
require => [
File['some_config_file'],
File['some_sysconfig_file'],
],
}
- 14 -
System Administration Using Puppet Certification Linux Academy
Quoting
All strings must be enclosed in single quotes, unless the string:
Contains variables
Is an enumerable set of options, such as present/absent, in which case the single quotes are
optional
Double quotes should be used rather than escaping when a string contains single quotes, unless that
would require an inconvenient amount of additional escaping.
Example
file { "/tmp${file_name}": }
"${facts['operatingsystem']} is not supported by ${module_name}"
warning("Class[class_name'] doesn't work they way you expected it too.")
Documentation comments for Puppet Strings should be included for each of your classes, defined
types, functions, and resource types and providers.
Example
# Configures sshd
file { '/etc/ssh/ssh_config': ... }
Module Metadata
Every module must have metadata defined in the metadata.json file.
- 15 -
System Administration Using Puppet Certification Linux Academy
Example
{
"name": "tthomsen-my_module_name",
"version": "0.1.0",
"author": "Travis N. Thomsen",
"license": "Apache-2.0",
"summary": "It's a modules that does things",
"source": "https://github.com/mygithubaccount/tthomsen-my_module_
name",
"project_page": "https://github.com/mygithubaccount/tthomsen-my_
module_name",
"issues_url": "https://github.com/mygithubaccount/tthomsen-my_module_
name/issues",
"tags": ["things", "and", "stuff"],
"operatingsystem_support": [
{
"operatingsystem":"RedHat",
"operatingsystemrelease": [
"5.0",
"6.0"
]
},
{
"operatingsystem": "Ubuntu",
"operatingsystemrelease": [
"12.04",
"10.04"
]
}
],
"dependencies": [
{ "name": "puppetlabs/stdlib", "version_requirement": ">= 3.2.0
<5.0.0" },
]
}
Resources
All resource names or titles must be quoted.
Resources should be grouped by logical relationship to each other, rather than by resource type.
Semicolon-separated multiple resource bodies should be used only in conjunction with a local
default body.
Example
file { '/etc/ssh/ssh_config':
- 16 -
System Administration Using Puppet Certification Linux Academy
Example
# /etc/puppetlabs/code/environments/production/modules/apache/manifests
# init.pp
class apache { }
# ssl.pp
class apache::ssl { }
# virtual_host.pp
define apache::virtual_host () { }
When a resource or include statement is placed outside of a class, node definition, or defined type, it
is included in all catalogs. This can have undesired effects and is not always easy to detect.
Example
#manifests/init.pp:
class { 'some_class':
include some_other_class
}
Example
# Points left to right
Package['package_name'] -> Service['service_name']
# On the line of the right-hand operand
Package['package_name']
-> Service['service_name']
Classes and defined types should be declared as close to node scope as possible.
- 17 -
System Administration Using Puppet Certification Linux Academy
Parameter
Declare required parameters before optional parameters.
Declare the data type of parameters, as this provides automatic type assertions.
For Puppet 4.9.0 and greater, use Hiera data in the module and rely on automatic parameter lookup
for class parameters.
Puppet versions less than 4.9.0, use the "params.pp" pattern. In simple cases, you can also specify
the default values directly in the class or defined type.
Example:
# parameter defaults provided via APL > puppet 4.9.0
class some_module (
String $source,
String $config,) {
... puppet code ...
}
Class Inheritance
Class inheritance should not be used.
Inheritance should only be used for params.pp, which is not recommended in Puppet 4.9.
For maintaining older modules inheritance can be used but must not be used across module
namespaces.
Example:
class ssh { ... }
class ssh::client inherits ssh { ... }
class ssh::server inherits ssh { ... }
- 18 -
System Administration Using Puppet Certification Linux Academy
Uniqueness
Variables
Referencing facts
When referencing facts, prefer the $facts hash to plain top-scope variables.
It's clearer.
Example: $facts['operatingsystem']
Namespacing variables
When referencing top-scope variables other than facts, explicitly specify absolute namespaces
for clarity and improved readability. This includes top-scope variables set by the node classifier and
in the main manifest.
Variable format
Use numbers
Use underscores
Good Examples:
$this_is_vairable
- 19 -
System Administration Using Puppet Certification Linux Academy
$so_is_this
$also_good123
Bad Examples:
$ThisIsNotGood
$neither-is-this
Conditionals
Keep resource declarations simple.
Example:
$file_mode = $facts['os']['family'] ? {
'Debian' => '0007',
'RedHat' => '0776',
default => '0700',
}
file { '/tmp/readme.txt':
ensure => file,
content => "Hello World\n",
mode => $file_mode,
}
case $Facts[::operatingsystem] {
'centos': { $version = '1.2.3' }
'debian': { $version = '3.4.5' }
default: { fail("Module ${module_name} is not supported on
${::operatingsystem}") }
}
Data Types
Core Data Types
The most common data types:
- 20 -
System Administration Using Puppet Certification Linux Academy
String
Boolean
Array
Hash
Regexp
Undef
Default
Scalar
Collection
Variant
Data
Pattern
Enum
Tuple
Struct
Optional
Catalogentry
Type
Any
Callable
- 21 -
System Administration Using Puppet Certification Linux Academy
Syntax:
Type[<ANY DATA TYPE>]
Example:
Type: matches any data type, such as Integer, String, Any, or Type.
Type[String]: matches the data type String, as well as any of its more specific subtypes like
String[3] or Enum["running", "stopped"].
Type[Resource]: matches any Resource data type - that is, any resource reference.
notify: Applies a resource before the target resource. The target resource refreshes if the notifying
resource changes.
subscribe: Applies a resource after the target resource. The subscribing resource refreshes if the
target resource changes.
Chaining Arrows
You can create relationships between two resources or groups of resources using the -> and ~> operators.
-> ordering arrow: Applies the resource on the left before the resource on the right.
~> notifying arrow: Applies the resource on the left first. If the left-hand resource changes, the
right-hand resource will refresh.
- 22 -
System Administration Using Puppet Certification Linux Academy
Resource declarations
Resource collectors
Ordering
All relationships cause Puppet to manage one or more resources before one or more other resources.
By default, unrelated resources are managed in the order in which they're written in their manifest file. If
you declare an explicit relationship between resources, it will override this default ordering.
service
mount
exec
Sometimes package
No-op
Auto relationships between types and resources are established when applying a catalog.
- 23 -
System Administration Using Puppet Certification Linux Academy
Missing Dependencies
If one of the resources in a relationship is not declared the catalog will fail to compile.
Failed Dependencies
If a resource with dependencies fails to be applied, all dependent resource will be skipped.
Dependency Cycles
If two or more resources require each other, Puppet compiles the catalog but it won't be applied
because this causes a loop.
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
Conditional Statements
Conditional statements let your Puppet code behave differently in different situations. They are most helpful
when combined with facts or with data retrieved from an external source.
if statement
unless statement
case statement
selector
"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.
- 24 -
System Administration Using Puppet Certification Linux Academy
Syntax:
if condition {
block of code
}
elsif condition {
block of code
}
else {
default option
}
Example:
if $facts['os']['name'] == 'Windows' {
include role::windows
}
elsif ($facts['os']['name'] == 'RedHat') and ($facts['os']['name'] ==
'CentOS') {
include role::redhat
}
elsif $facts['os']['name'] =~ /^(Debian|Ubuntu)$/ {
include role::debian
}
else {
include::generic::os
}
Behavior
If none of the conditions match and there is no else block, Puppet will do nothing.
Conditions
Variables
If you use a regular expression match operator as your 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:
Example:
if $trusted['certname'] =~ /^www(\d+)\./ {
notice("This is web server number $1.")
- 25 -
System Administration Using Puppet Certification Linux Academy
"Unless" statements
"Unless" is the reversed "if" statements. It takes a boolean condition and an arbitrary block of Puppet code.
It will only execute the block of code if the condition is false. There cannot be a elsif clauses.
Syntax:
unless condition {
block of code
}
Example:
unless $facts['memory']['system']['totalbytes'] > 1073741824 {
$maxclient = 500
}
Behavior
The condition is evaluated first and, if it is false, the code block is executed.
The unless statement is also an expression that produces a value, and can be used wherever a
value is allowed.
Conditions
Variables
Although "unless" statements receive regex capture variables like "if" statements, they usually
aren't used.
Case Statements
Similar to the "if" statements, case statements choose one of several blocks of arbitrary Puppet code.
Syntax:
case condition {
- 26 -
System Administration Using Puppet Certification Linux Academy
Example:
case $facts['os']['name'] {
'Windows': { include role::windows }
'RedHat', 'CentOS': { include role::redhat }
/^(Debian|Ubuntu)$/: { include role::debian }
default: { include::generic::os }
}
Behavior
Compares the control expression to each of the cases in the order they are defined.
Conditions
Variables
Case matching
Default matches anything, and unless nested inside an array or hash, is always tested last,
regardless of its position in the list.
In addition to executing the code in a block, a case statement is also an expression that produces
a value, and can be used wherever a value is allowed.
- 27 -
System Administration Using Puppet Certification Linux Academy
The value of a case expression is the value of the last expression in the executed block, or undef
if no block was executed.
If you use a regular expression match operator as your 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:
Example:
case $trusted['certname'] {
/www(\d+)/: { notice("This is web server number $1."); }
default: { notice("Now for something completely different") }
}
Selectors
Selector expressions are similar to case statements, but return a value. You should generally only use
selectors in variable assignments.
Syntax:
case condition {
'control expression': { block of code }
default: { block of code }
}
Example:
$role = $facts['os']['name'] ? {
'Windows' => 'role::windows',
/^(Debian|Ubuntu)$/ => 'role::debian',
default => 'role::redhat',
}
Behavior
The control expression is compared to each of the cases in the order they are defined.
Conditions
- 28 -
System Administration Using Puppet Certification Linux Academy
Variables
Case matching
default matches anything, and unless nested inside an array or hash is always tested last,
regardless of its position in the list.
If you use a regular expression match operator as your 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:
Example:
$role = $facts['os']['name'] ? {
/^(Debian|Ubuntu)$/ => "You are running ${1}",
default => "You are running an unknown operating system!",
}
- 29 -
System Administration Using Puppet Certification Linux Academy
Numbers
Underscores
'$variable += ['c']'
Arrays
When using an array you need an equal number of variables and values.
Hashes
Variables are listed in an array on the left side of the assignment operator.
Variable Interpolation
Variable interpolation is when a variables is resolved in a double-quoted strings.
Inside the double-quoted strings the variable is referenced using a dollar sign with curly braces.
- 30 -
System Administration Using Puppet Certification Linux Academy
${var_name}
Example:
$variable = "${some_other_variable} is being interpolation in here."
There are functions that take arrays as parameters, including the iteration functions like each.
Hashes
The entries are maintained the order they were added in.
Array Example:
$array_variable = [ 'a', 'b', 'c' ]
Hash Example:
$hash_variable = { key1 => "value1", key2 => "value2" }
Scope
Scope is a specific area of code that is partially isolated from other areas of code.
Top scope
Code that is outside any class definition, type definition, or node definition exists at top scope.
Variables and defaults declared at top scope are available everywhere.
Node scope
Code inside a node definition exists at node scope. Note that since only one node definition can
match a given node, only one node scope can exist at a time.
Local scopes
Code inside a class definition, defined type, or lambda exists in a local scope.
- 31 -
System Administration Using Puppet Certification Linux Academy
Variables and defaults declared in a local scope are only available in that scope and its children.
Metaparameters
Metaparameters are attributes that all resource type, custom types and defined types have.
Available Metaparameters
alias
audit
before
consume
export
loglevel
noop
notify
require
schedule
stage
subscribe
tag
Example:
file { '/etc/ssh/sshd_config':
owner => root,
group => root,
alias => 'sshdconfig',
}
service { 'sshd':
subscribe => File['sshdconfig'],
}
each: Repeat a block of code any number of times, using a collection of values to provide
different parameters each time.
slice: Repeat a block of code any number of times, using groups of values from a collection
as parameters.
filter: Use a block of code to transform some data structure by removing non-matching
elements.
map: Use a block of code to transform every value in some data structure.
reduce: Use a block of code to create a new value or data structure by combining values from
a provided data structure.
with: Evaluate a block of code once, isolating it in its own local scope. Doesn't iterate, but has
a family resemblance to the iteration functions.
Example:
$values = ['a', 'b', 'c', 'd', 'e']
# function call with lambda:
$values.each |String $value| {
notice { "Value from a lambda code block: ${value}": }
}
Syntax:
Class <CLASS NAME> (
<DATA TYPE> <PARAMETER NAME>,
<DATA TYPE> <PARAMETER NAME> = <VALUE>,
# ...
) {
# ...
}
Example:
class ntp (
Boolean $service_manage = true,
Boolean $autoupdate = false,
String $package_ensure = 'present',
# ...
) {
- 33 -
System Administration Using Puppet Certification Linux Academy
# ...
}
params.pp
The main classes inherit from a <MODULE>::params class, which only sets variables.
Using a function or Hiera to your defaults data is now the recommended method.
Puppet will try to find the requested data as a key in that hash.
A Ruby function (using the modern Puppet::Functions API), located at <MODULE ROOT>/
lib/puppet/functions/<MODULE NAME>/data.rb.
Example:
# ntp/metadata.json
{
...
"data_provider": "function"
}
# ntp/functions/data.pp
function ntp::data() {
$base_params = {
'ntp::autoupdate' => false,
'ntp::service_name' => 'ntpd',
}
$os_params = case $facts['os']['family'] {
'AIX': {
{ 'ntp::service_name' => 'xntpd' }
}
'Debian': {
{ 'ntp::service_name' => 'ntp' }
}
default: {
{}
- 34 -
System Administration Using Puppet Certification Linux Academy
}
}
# Merge the hashes and return a single hash.
$base_params + $os_params
}
# ntp/manifests/init.pp
class ntp (
# default values are in ntp/functions/data.pp
$autoupdate,
$service_name,
) {
...
}
Puppet Functions
There are two types of functions in statements and rvalues functions.
Functions
Statements
Rvalues
variable assignment
case statement
Statement Functions
create_resources: Converts a hash into a set of resources and adds them to the catalog.
hiera_include: Uses an array merge lookup to retrieve the classes array, so every node gets
every class from the hierarchy.
include: Declares one or more classes, causing the resources in them to be evaluated and
added to the catalog.
Rvalue Functions
defined: Determines whether a given class or resource type is defined and returns a Boolean
value.
file: Loads a file from a module and returns its contents as a string.
generate: Calls an external command on the Puppet master and returns the results of the
command.
hiera: Performs a standard priority lookup of the hierarchy and returns the most specific value
for a given key.
hiera_array: Finds all matches of a key throughout the hierarchy and returns them as a
single flattened array of unique values.
hiera_hash: Finds all matches of a key throughout the hierarchy and returns them in a
merged hash.
template: Loads an ERB template from a module, evaluates it, and returns the resulting value
as a string.
Templates
template: Loads an ERB template from a module, evaluates it, and returns the resulting value as a
string.
template('modulename/motd.erb')
Example:
file { '/etc/motd':
ensure => file,
content => template('modulename/motd.erb')
}
- 36 -
System Administration Using Puppet Certification Linux Academy
Puppet uses the template and inline_template functions to evaluate a template file.
Expression-printing:
<%= @value %>
If statement:
<% if condition %> ...text... <% end %>
Comments:
<%# This is a comment. %>
Looping:
<% @valuse.each -%>
<% do |values| %>some value <%= value %>
<% end -%>
Are blocks of code that can be evaluated multiple times with different parameters.
Each namespace segment must begin with a lowercase letter and can include:
Lowercase letters
Digits
Underscores
- 37 -
System Administration Using Puppet Certification Linux Academy
\\A[a-z]\[a-z0-9_\]\*\\Z
define_name123
Multiple namespace segments can be joined together in a define type name with the :: (double
colon) namespace separator.
\\A(\[a-z\][a-z0-9_]\*)?(::[a-z]\[a-z0-9_]\*)\*\\Z
module_name::defined_type_name
Syntax:
define name (
<DATA TYPE> <PARAMETER> = <VALUE>,
) {
... puppet code ...
}
Declaring an Instance:
<DEFINED TYPE> { '<TITLE>':
<ATTRIBUTE> => <VALUE>,
}
Example:
define apache::vhost (
Integer $port,
String[1] $docroot,
String $servername = $title,
String[1] $vhost_name = '*',
) {
# ...
}
apache::vhost {'mywebsite':
port => 80,
docroot => '/var/www/mywebsite',
}
Resource Collectors
Resource collectors also called the spaceship operator.
It selects a group of resources by searching the attributes of every resource in the catalog.
- 38 -
System Administration Using Puppet Certification Linux Academy
Operators
==
!=
and
or
Syntax:
<RESOURCE TYPE> <| <SEARCH EXPRESSION> |>
Example:
User <| groups == 'admin' |>
Exported Resources
Exported resources require catalog storage and searching to be enabled on your Puppet master.
Both the catalog storage and the searching (among other features) are provided by PuppetDB.
Any node can then collect the exported resource and manage its own copy of it.
Purpose
Exported resources allow the Puppet compiler to share information among nodes by combining
information from multiple nodes' catalogs.
- 39 -
System Administration Using Puppet Certification Linux Academy
This helps you manage things that rely on nodes knowing the states or activity of other nodes.
Syntax:
class <CLASS NAME> {
# Declare:
@@<RESOURCE BEING EXPORTED> { <TITLE>:
<ATTRIBUTE> => <VALUE>,
}
# Collect:
<REFERENCE RESOURCE BEING EXPORTED> <<| |>>
}
Example:
class ssh {
# Declare:
@@sshkey { $::hostname:
type => dsa,
key => $::sshdsakey,
}
# Collect:
Sshkey <<| |>>
}
Syntax:
@@<RESOUCE TYPE> { <TITLE>:
<ATTRIBUTE> => <VALUE>,
}
NTP Module
ntp.conf.erb
# File Managed by Puppet
# For more information about this file, see the man pages
# ntp.conf(5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_
mon(5).
driftfile /var/lib/ntp/drift
# Permit time synchronization with our time source, but do not
# permit the source to query or modify the service on this system.
restrict default nomodify notrap nopeer noquery
- 40 -
System Administration Using Puppet Certification Linux Academy
Exported Resources
[puppet-sshkeys]
- 41 -
System Administration Using Puppet Certification Linux Academy
The roles and profiles are used to build reliable, reusable, configurable, and refactorable system configurations.
They are two extra layers of indirection between your node classifier and your component modules.
(Component modules: Normal modules that manage one particular technology. (For example,
puppetlabs/apache.)
Profiles: Wrapper classes that use multiple component modules to configure a layered technology
stack.
Roles: Wrapper classes that use multiple profiles to build a complete system configuration.
Profiles
A profile is just a normal class stored in the profile module.
Make sure you can safely include any profile multiple times don't use resource-like declarations
on them.
Profiles own all the class parameters for their component classes.
There are three ways a profile can get the data it needs to configure component classes:
Example:
class profiles::apache(
String $apache_vhost_name,
String $apache_vhost_docroot,
Bolean $apache_default_vhost = false,
String $apache_vhost_port = 80,
) {
class { 'apache':
default_vhost => $apache_default_vhost,
}
apache::vhost { $apache_vhost_name:
port => $apache_vhost_port,
docroot => $apache_vhost_docroot,
}
}
Roles
The only thing roles should do is declare profile classes.
- 42 -
System Administration Using Puppet Certification Linux Academy
The name of a role should be based on your business's conversational name for the type of node it
manages.
Example:
class role::web {
include profile::base
include profile::apache
include profile::php
}
Hiera Overview
Hiera is a key/value datastore for looking up data.
Setting Up Hiera
The hiera.ya ml file is located in /etc/puppetlabs/puppet/.
:backends: tells Hiera what kind of data sources it should process. In this case, we'll be using
YAML files.
hiera.yaml
---
:backends:
- yaml
:ya ml:
:datadir: "/etc/puppetlabs/code/environments/%{environment}/hieradata"
:hierarchy:
- "nodes/%{::trusted.certname}"
- common
If no pass parameter it will look in hiera data source for the parameter <CLASS
NAMESPACE>::parameter
If not found in hiera data source it will use the default set "default"
- 44 -
System Administration Using Puppet Certification Linux Academy
Arguments:
An optional default value to return if Hiera doesn't find anything matching the key.
The optional name of an arbitrary hierarchy level to insert at the top of the hierarchy.
hiera_array:
Finds all matches of a key throughout the hierarchy and returns them as a single flattened array of unique
values. If any of the matched values are arrays, they're flattened and included in the results. This is called
an array merge lookup.
Arguments:
An optional default value to return if Hiera doesn't find anything matching the key.
The optional name of an arbitrary hierarchy level to insert at the top of the hierarchy.
hiera_hash:
Finds all matches of a key throughout the hierarchy and returns them in a merged hash. If any of the
matched hashes share keys, the final hash uses the value from the highest priority match. This is called a
hash merge lookup.
Arguments:
An optional default value to return if Hiera doesn't find anything matching the key.
The optional name of an arbitrary hierarchy level to insert at the top of the hierarchy.
- 45 -
System Administration Using Puppet Certification Linux Academy
Code Manager automates the management and deployment of your new Puppet code.
Installs modules.
You can r10k to manage your Puppet code instead of Code Manager.
wget https://github.com/puppetlabs/control-repo/archive/production.zip
yum install unzip -y
unzip production.zip
cd production
Click Repositories.
- 46 -
System Administration Using Puppet Certification Linux Academy
Check in code.
Push code.
git init
git remote add origin <URL_TO_REPOSITORY>
git commit -am "first commit"
git push origin master
mkdir -p /etc/puppetlabs/puppetserver/ssh
ssh-keygen -t rsa -b 4096 -C "[email protected]"
/etc/puppetlabs/puppetserver/ssh/id_rsa
code_manager_auto_configure to true
/etc/puppetlabs/puppetserver/ssh/id_rsa
Nginx Module
nginx.conf.erb
# File Managed by Puppet
user <%= @process_user %>;
worker_processes <%= @processorcount %>;
error_log <%= @log_dir %>/error.log;
pid <%= @pid_file %>;
events {
worker_connections 1024;
}
http {
server_tokens off;
include <%= @config_dir %>/mime.types;
default_type application/octet-stream;
access_log <%= @log_dir %>/access.log;
sendfile on;
#tcp_nopush on;
tcp_nodelay on;
include <%= @confd %>/*.conf;
<% if @vdir_enable %>
include <%= @vdir_enable %>/*;
<% end %>
}
- 48 -
System Administration Using Puppet Certification Linux Academy
vhost.conf.erb
# File Managed by Puppet
server {
listen <%= @port %>;
root <%= @vhost_docroot %>;
server_name <%= @name %> <%= @serveraliases %>;
access_log <%= @log_dir %>/<%= @name %>.access.log;
error_log <%= @log_dir %>/<%= @name %>.error.log;
}
Node Classification
Node Definition Lookup
Node Definition Lookup Example: webserver01.mylabserver.com
Attempt to webserver01.mylabserver
Attempt to webserver01
Match Default
Note: if a node matches multiple node definitions due to regular expressions, puppet will use ONE of them
with no guarantee as to which one it will use.
Default node_terminus=classifier
Example:
[master]
node_terminus = exec
- 49 -
System Administration Using Puppet Certification Linux Academy
external_nodes = /usr/local/bin/puppet_node_classifier
Add hiera_include('classes'))
Example:
# Assuming apache.ya ml:
classes:
- role::apache
# Assuming common.ya ml:
classes:
- role::base
Any classes or resources which are in the site manifest but outside any node definitions
Tools:
puppet job
Allows you to manage and enforce the order if Puppet agent runs across an environment.
- 50 -
System Administration Using Puppet Certification Linux Academy
Enforces the order of agent runs by instantiating an application model and assigning nodes
to application components.
puppet app
Lets you view the application models and application instances written and stored on the
Puppet master.
You control when Puppet runs and where node catalogs are applied.
You no longer need to wait on arbitrary run times to update your nodes.
Orchestrator Workflow
Write Puppet code to be uses with Puppet Application Orchestration.
puppet app show command to validate that your application or application instances looks
correct.
puppet job plan command to show applications or application instances and the node run order
that would be included in a job.
puppet job run command to enforce change on your infrastructure and configure your
application.
MCollective Overview
Overview
Puppet Enterprise includes the MCollective.
MCollective Plugins:
- 51 -
System Administration Using Puppet Certification Linux Academy
puppet: Run Puppet agent, get its status, and enable/disable it.
rpcutil: General helpful actions that expose stats and internals to SimpleRPC clients.
MCollective Components:
pe-activemq: Service (which runs on the Puppet master server) routes all MCollective-related
messages.
pe-mcollective: Service (which runs on every agent node) listens for authorized commands and
invokes actions in response.
mco command (available to the peadmin user account on the Puppet master server) can issue
authorized commands to any number of nodes.
Using MCollective
To run MCollective commands you must:
Using sudo
sudo -i -u peadmin
Add the user's public SSH keys to peadmin's authorized keys file.
/var/lib/peadmin/.ssh/authorized_keys
- 52 -
System Administration Using Puppet Certification Linux Academy
/var/lib/peadmin/.m collective
Synstax:
mco <SUBCOMMAND> <ACTION>
mco rpc <AGENT PLUGIN> <ACTION> <INPUT>=<VALUE>
Examples:
mco ping
mco rpc rpcutil ping
mco rpc service restart service=puppet
Host Filters
-W, --with FILTER Combined classes and facts filter
-C, --wc, --with-class CLASS Match hosts with a certain config management class
-I, --wi, --with-identity IDENT Match hosts with a certain configured identity
Troubleshooting
Common Installer Problems
Check your DNS
If you are installing the console and the Puppet master on separate servers and tried to install the
console first, the installer may fail.
- 53 -
System Administration Using Puppet Certification Linux Academy
If you encounter errors during installation, you can fix them and run the installer again.
Troubleshooting Connections
Troubleshooting connections between components
Make sure the agent can reach the DNS name that is configured in puppet.conf.
On the master:
On the agent:
rm -r $(puppet agent --configprint ssldir) puppet agent -t
(or --test)
err: /Stage[main]/Pe_mcollective/File[/etc/puppetlabs/mcollective/
server.cfg]
/content:change from {md5}778087871f76ce08be02a672b1c48bdc to{md5}
e33a27e4b9a
87bb17a2bdff115c4b080 failed: Could not back up/etc/puppetlabs/
mcollective/se
rver.cfg: getaddrinfo: Name or service not known
Example:
# Define filebucket 'main':
filebucket { 'main':
server => '<PUPPET MASTER'S DNS NAME>',
path => false,
}
- 54 -
System Administration Using Puppet Certification Linux Academy
General Troubleshooting
Use --profil or add profile to true in the agent's puppet.conf file.
Database Troubleshooting
Troubleshoot classification
Determine What Node Groups the NC Has and What Data They Contain:
curl https://$(hostname -f):4433/classifier-api/v1/groups > classifier_
groups.json
--cacert /etc/puppetlabs/puppet/ssl/certs/ca.pem
--cert /etc/puppetlabs/puppet/ssl/certs/<WHITELISTED CERTNAME>.pem
--key /etc/puppetlabs/puppet/ssl/private_keys/<WHITELISTED
CERTNAME>.pem
Determine What Data the NC Will Generate for a Given Node Name:
curl https://$(hostname -f):4433/classifier-api/v1/classified/
nodes/<SOME NODE NAME> > node_classification.json
--cacert /etc/puppetlabs/puppet/ssl/certs/ca.pem
--cert /etc/puppetlabs/puppet/ssl/certs/<WHITELISTED CERTNAME>.pem
--key /etc/puppetlabs/puppet/ssl/private_keys/<WHITELISTED
CERTNAME>.pem
Check /var/log/pe-postgresql/pgstartup.log
FATAL: could not create shared memory segment: No space left
on deviceDETAIL: Failed system call was shmget(key=5432001,
size=34427584512,03600).
Tweaking the machine's shmmax and shmall kernel settings before installing PE.
shmall should be calculated by dividing the new shmmax setting by the PAGE_SIZE.
- 55 -
System Administration Using Puppet Certification Linux Academy
You need to update the setting in the console or they will be overwritten.
Vacuuming PostgreSQL
su - pe-postgres -s /bin/bash -c "vacuumdb -z --verbose <DATABASE NAME>"
Backing Up PostgreSQL
sudo -u pe-postgres /opt/puppetlabs/server/apps/postgresql/bin/pg_
dumpall -c -f <BACKUP_FILE>.sql
Reporting
Information found on reports:
Skipped: How many resources were skipped (either due to tags or schedule metaparameter).
Scheduled: How many resources met the scheduling restriction, if one is present.
Out of Sync: How many resources were out of sync (not in the desired configuration state).
Applied: How many resources were aelempted to be put into the desired configuration state.
- 56 -
System Administration Using Puppet Certification Linux Academy
Failed: How many resources were not successfully fixed (put into the desired configuration
state).
How long it took to retrieve the configuration (compiled catalog) from the puppet master.
store: store reports in yaml form in the location specified in the reportdir setting
Removing Nodes
You will need to do the following step to remove a node from Puppet Enterprise:
- 57 -
System Administration Using Puppet Certification Linux Academy
Pearson VUE
Profiles Repository
Control Repository
NTP Repository
SSH Repository
Nginx Repository
- 58 -