System Administration Using Puppet

What is Puppet?
§ The Puppet’s language is declarative
§ Puppet code is written to express desired end state of the node
§ Management of node resource are abstracted from the operating system
§ Code is written inside of classes, classes are assigned to nodes
§ Puppet was founded by Luke Kanies in 2005
§ Written in Ruby and Clojure

Agent Components (On All Nodes)
§ Puppet agent is the software used to communicate with the Puppet master to
execute a Puppet run.
§ Puppet is the core of our configuration management platform. It consists of a
special programming language for describing desired system states, an agent that
can enforce desired states, and several other tools and services.
§ Facter is a system profiling tool. Puppet agent uses it to send important system
info to Puppet Server, which can access that info when compiling that node’s
catalog.
§ Hiera is a hierarchical data lookup tool. You can use it to configure your Puppet
classes.
§ MCollective (Marionette Collective) is a framework for building server
orchestration or parallel job-execution systems.
§ Puppet Server is the JVM application that provides Puppet’s core HTTPS services.
Whenever Puppet agent checks in to request a configuration catalog for a node, it
contacts Puppet Server.
§ PuppetDB collects the data Puppet generates and offers a powerful query API for
analyzing that data. It’s the foundation of the PE console, and you can also use
the API to build your own applications.
§ R10k is a code management tool that allows you to manage your environmental
configurations (such as production, testing, and development) in a source control
repository.
§ Razor Server is a PXE boot provisioning application that deploys bare-metal
systems.
§ PostgreSQL is an open source relational database management system used by
PuppetDB.
§ ActiveMQ is the message broker used by MCollective.
§ Nginx is the web server used by the Puppet Enterprise Console.
§ Console Puppet Enterprise’s web interface.

Puppet Enterprise Client Tools
§ Puppet orchestrator allows you to control the rollout of changes in your
infrastructure and provides the interface to the Puppet Application Orchestration
service.
§ Puppet access is a tool used to authenticate yourself to the PE RBAC token-based
authentication service so that you can use other capabilities and APIs.
§ Code Manager provides the interface for the Code Manager and file sync
services.
§ PuppetDB CLI is a tool for working with PuppetDB, such as building queries and
handling exports.

Puppet Master vs. Puppet Server vs. Puppet Master Server
§ Puppet master is a Ruby application that compiles configurations for any number
of Puppet agent nodes, using Puppet code and various other data sources.
§ Puppet Server is an application that runs on the Java Virtual Machine (JVM) and
provides the same services as the classic Puppet master application.
§ Puppet Master Server (Puppet Master) is the server that performs the catalog
compile.

What is a Catalog?
When a node checks into the Puppet master server it retrieves a document called a
catalog. The catalog describes the desired state of the node being managed. It may
also specify dependency information for the resources that should be managed in a
certain order. This is essentially a compiled version of the DSL and is compiled on the
Puppet master and stored in PuppetDB.

Puppet Nodes (Agents)
§ Nodes are virtual, physical or non-ephemeral cloud systems
§ Runs the Puppet agent
Required ports:
§ 8140 for the Puppet agent
§ 61613 for MCollective

mportant Ports
§ 3000: Used for the web-based installer of the Puppet master.
§ 8140: The port on which the Puppet master and agents communicate.
§ 61613: Used by MCollective for orchestration requests by Puppet agents.
§ 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.
§ 8081: The PuppetDB traffic/request port.
§ 8142: Used by Orchestration services to accept inbound traffic/responses from
the Puppet agents.

Resource Abstraction Layer
A resource declaration is an expression that describes the desired state for a resource and tells
Puppet to add it to the catalog. When Puppet applies that catalog to a target system, it
manages every resource it contains, ensuring that the actual state matches the desired state.
Providers implement the same resource type on different kinds of systems. They usually do this
by calling out to external commands.
Example:
§ RedHat/CentOS uses yum and RPM
§ Debian/Ubuntu uses apt-get andDPKG
§ Ruby uses gems
Resources
§ When building modules, we are using the Puppet DSL to declare the desired state of
resources on a node.
§ Fundamentally, all we are doing with Puppet is managing resources on a large and
automated scale while caring “as little as possible” about the platform/distribution.
§ In Puppet we are using resource types to define instances of a resource on a node.
§ https://docs.puppet.com/puppet/latest/type.html

Commands
§ puppet resource: View resources already installed on a node (node level)
§ puppet resource [type]
§ puppet resource [type] [name]
§ puppet resource user
§ puppet resource user root
§ puppet describe: Provide information about resource types within puppet
§ puppet describe –l (list all resource types available)
§ puppet describe –s [type]
§ puppet describe [type]
Catalog Compilation
§ A catalog describes the desired state for each resource on the node
§ The catalog is compiled on the master
§ The compiled catalog is shipped to the node during the Puppet run
§ The desired state is enforced on the node by the catalog
§ The catalog is stored in PuppetDB
§ Default on PE install
§ Puppet compiles the catalog using sources of configuration info
§ Agent-provided data (Facts)
§ External data (Hiera)
§ Puppet manifests (Puppet code)
§ Retrieve the node object
§ Node object provides factual information about a node
§ Set scope-level variables
§ Set variables from the node object, facts, and the certificate
§ Variables provided by the node object will now be set as top-scope
§ Node’s facts are also set as top-scope variables
§ Variables provided by the Puppet master will also be set
§ Evaluate the main manifest (site.pp)
§ Match any matching node definitions
§ Load and evaluate classes from modules
§ The environmentpath setting in puppet.conf tells Puppet where to find environments.
§ /etc/puppetlabs/code/environments//modules
§ Default environment is production
§ Evaluate classes from the node object
§ Variables provided by the node object will be set as top-scope
§ Node’s facts are set as top-scope variables
§ Variables provided by the Puppet master will be set
Certificate Signing Request
Puppet Server includes a certificate authority (CA) service that accepts certificate signing
requests (CSRs) from nodes, serves certificates and a certificate revocation list (CRL) to nodes,
and optionally accepts commands to sign or revoke certificates.
§ When you install a new PE agent, the agent will automatically submit a certificate signing
request (CSR) to the Puppet master.
§ Before Puppet agent nodes can retrieve their configuration catalogs, the certificate needs
to be signed by the certificate authority (CA).
Certificate Signing Request
Command:
puppet cert
puppet cert list
puppet cert sign
puppet cert revoke
DNS altnames:
puppet cert sign ( or –all) –allow-dns-alt-names

Regenerating Certificates
§ On the Puppet master:
§ puppet cert clean
§ Deleting SSL certs on agent:
§ cp -r /etc/puppetlabs/puppet/ssl/ /etc/puppetlabs/puppet/ssl_bak/

Creating module first and adding it to git for code review

modules

[root@docker ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory ‘/root/.ssh’.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
3e:a7:7a:14:94:01:17:29:38:78:2a:48:d2:d8:d7:8c root@docker
The key’s randomart image is:
+–[ RSA 2048]—-+
| + . =..+= |
|o.+ E +.+ |
|+ + . o |
|o . . |
| . S. |
| .. |
| .o . |
| .+ |
| .o. |
+—————–+

[root@docker ~]# cat .ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDG5a0YA3hE8k5tP/px103MdPgjbGbaVbfk/4uAMSno7ys1b1Js4L7MLYxHNUgoEOD5HSFvflq3UjdYTvd8GeiQAzwvppe97vj1+GPMFAf50f5Dj9WRJkOrlPVzBFc8B8jw3C/uPlfQq0wveYF6YY9vN/1NOOSi6rbf7l+s5vhaX2IE0BxHY9Cg4AUqsIId9GHQKpW2vPIYXCLf1pddIyartMIT3t5tsJD9Uksnvb4Bw4kNM6kUpenjKYF3qxJ8ty5o6c/S7kCE6mKpcNuxA0RBwwS8z3kxxDzlwt3DRUtSwVHhsYowI61t+wv6D8srMZzarjUCqfICDMSCXKS+BeuD root@docker

login into https://github.com/

add ssh-key  and create repository 

git@github.com:rafi494/puppet-ssh.git

[root@docker ~]# puppet module generate rafi494-ssh
We need to create a metadata.json file for this module. Please answer the
following questions; if the question is not applicable to this module, feel free
to leave it blank.

Puppet uses Semantic Versioning (semver.org) to version modules.
What version is this module? [0.1.0]
–>

Who wrote this module? [rafi494]
–>

What license does this module code fall under? [Apache 2.0]
–>

How would you describe this module in a single sentence?
–>

Where is this module’s source code repository?
–> git@github.com:rafi494/puppet-ssh.git

Where can others go to learn more about this module?
–>

Where can others go to file issues about this module?
–>

—————————————-
{
“name”: “rafi494-ssh”,
“version”: “0.1.0”,
“author”: “rafi494”,
“summary”: null,
“license”: “Apache 2.0”,
“source”: “git@github.com:rafi494/puppet-ssh.git“,
“project_page”: null,
“issues_url”: null,
“dependencies”: [
{“name”:”puppetlabs-stdlib”,”version_requirement”:”>= 1.0.0″}
]
}
—————————————-

About to generate this metadata; continue? [n/Y]
–> y

Notice: Generating module at /root/rafi494-ssh…
Notice: Populating templates…
Finished; module generated in rafi494-ssh.
rafi494-ssh/Rakefile
rafi494-ssh/manifests
rafi494-ssh/manifests/init.pp
rafi494-ssh/spec
rafi494-ssh/spec/classes
rafi494-ssh/spec/classes/init_spec.rb
rafi494-ssh/spec/spec_helper.rb
rafi494-ssh/tests
rafi494-ssh/tests/init.pp
rafi494-ssh/Gemfile
rafi494-ssh/README.md
rafi494-ssh/metadata.json

[root@docker ~]# ls -l
total 4
drwxr-xr-x 5 root root 110 May 20 00:43 rafi494-ssh
[root@docker ~]# cd rafi494-ssh/
[root@docker rafi494-ssh]# ls -l
total 16
-rw-r–r– 1 root root 242 May 20 00:43 Gemfile
drwxr-xr-x 2 root root 20 May 20 00:43 manifests
-rw-r–r– 1 root root 310 May 20 00:43 metadata.json
-rw-r–r– 1 root root 633 May 20 00:43 Rakefile
-rw-r–r– 1 root root 2883 May 20 00:43 README.md
drwxr-xr-x 3 root root 41 May 20 00:43 spec
drwxr-xr-x 2 root root 20 May 20 00:43 tests
[root@docker rafi494-ssh]#  yum install git -y
[root@docker rafi494-ssh]# git init
Initialized empty Git repository in /root/rafi494-ssh/.git/
[root@docker rafi494-ssh]# git add .
[root@docker rafi494-ssh]# git commit -am “Init commit”
[master (root-commit) 1e96716] Init commit
Committer: root <root@docker.c.rising-artifact-164906.internal>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

git config –global user.name “Your Name”
git config –global user.email you@example.com

After doing this, you may fix the identity used for this commit with:

git commit –amend –reset-author

8 files changed, 179 insertions(+)
create mode 100644 Gemfile
create mode 100644 README.md
create mode 100644 Rakefile
create mode 100644 manifests/init.pp
create mode 100644 metadata.json
create mode 100644 spec/classes/init_spec.rb
create mode 100644 spec/spec_helper.rb
create mode 100644 tests/init.pp
[root@docker rafi494-ssh]# git remote add origin git@github.com:rafi494/puppet-ssh.git

[root@docker rafi494-ssh]# git push origin master
The authenticity of host ‘github.com (192.30.253.113)’ can’t be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘github.com,192.30.253.113’ (RSA) to the list of known hosts.
Counting objects: 14, done.
Compressing objects: 100% (11/11), done.
Writing objects: 100% (14/14), 3.61 KiB | 0 bytes/s, done.
Total 14 (delta 0), reused 0 (delta 0)
To git@github.com:rafi494/puppet-ssh.git
* [new branch] master -> master

https://github.com/rafi494/puppet-ssh

Classes

Puppet Classes
§ Classes are named blocks of Puppet code that are used in a modules.
§ They are not applied until they are invoked by name.
§ They can be added to a node’s catalog by declaring it in a manifest or in the ENC.
§ They use Resource Types to configure packages, files, services, etc.
§ Classes can use parameters to request external data.
§ A default parameter should be supplied.
§ Each parameter can be preceded by an optional data type.
§ Classes are singletons.
§ Class names can consist of one or more namespace segments.
§ Each namespace segment must begin with a lowercase letter and can include:
§ Lowercase letters
§ Digits
§ Underscores
§ Namespace segments should match the following regular expression:
§ \A[a-z][a-z0-9_]*\Z
§ class_name123
§ Multiple namespace segments can be joined together in a class name with the :: (double
colon) namespace separator.
§ \A([a-z][a-z0-9_]*)?(::[a-z][a-z0-9_]*)*\Z
§ module_name::class_name
Puppet Classes
Class syntax:
class (
) {
… puppet code …
}
Example:
class ssh {
file { “/etc/ssh/ssh_config”:
ensure => file,
source => “puppet:///modules/ssh/ssh_config”
}
}

Class Variables
§ Variable names begin with a $ (dollar sign) and are case-sensitive.
§ Variable names can include:
§ Uppercase and lowercase letters
§ Numbers
§ Underscores (_)
§ There are reserved variable names:
§ Data Types
§ Function names

Creating a Module
§ Modules are self-contained bundles of code and data used to manage a single piece of
technology.
§ How to generate a module
§ puppet module generate –
§ The tests directory deprecated
§ The examples directory has been added
§ Module names contain
§ Lowercase letters
§ Numbers
§ Underscores
§ Should begin with a lowercase letter
§ Module names cannot contain the namespace separator ( :: )
§ Modules cannot be nested
Module Layout
§
o manifests
o files
o templates
o lib
o facts.d
o examples
o spec
o functions
o types

Important Directories
§ manifests/ – Contains all of the manifests in the module.
§ files/ – Contains static files, which managed nodes can download.
§ lib/ – Contains plugins, like custom facts and custom resource types.
§ facts.d/ – Contains external facts, which are an alternative to Ruby-based custom facts.
§ templates/ – Contains templates, which the module’s manifests can use.
§ examples/ – Contains examples showing how to declare the module’s classes and defined
types.

Facter
§ Facter is Puppet’s cross-platform system profiling library. It discovers and reports per-node
facts, which are available in your Puppet manifests as variables.
§ Core Facts: Built-in fact that ships with Facter
§ External Facts: Provide a way to use arbitrary executables or scripts as facts
§ Custom Facts: Extend Facter by writing Ruby code
§ Facter Command
§ facter: Returns a list all facts.
§ facter : Returns a particular fact.
§ facter -p: Allows Facter to load Puppet-specific facts.

Custom Facts
§ Custom facts are snippets of Ruby code on the Puppet master.
§ Usually shell commands are issued as part of the fact to return information.
§ Executed on the Puppet nodes with the External Facts Plugin Module.
§ Custom facts are located in lib/facter.
§ Facter offers multiple methods of loading facts:
§ $LOAD\_PATH, or the Ruby library load path
§ The –custom-dir command line option
§ The environment variable ‘FACTERLIB’
§ Facts distributed using pluginsync
§ Enabled in the [main] section of puppet.conf by setting pluginsync=true

Custom Facts
Example:
# hardware_platform.rb
Facter.add(‘hardware_platform’) do
setcode do
Facter::Core::Execution.exc(‘/bin/uname –hardware-platform’)
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:
§ //facts.d/
§ On Unix/Linux/OSX:
§ /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\
External Facts
§ For Facter to parse the output, the script must return key/value pairs on STDOUT in the
format:
§ key1=value1
§ key2=value2
§ key3=value3
§ Structured data facts:
§ yaml
§ json
§ txt

Resource Types: Review
§ Resource types are the basic building blocks of the Puppet DSL.
§ Every resource type has:
§ a title
§ a set of attributes
Resource Type Syntax:
{ ”: => , } § The attributes (sometimes called parameters) of a resource determine its desired state. Common Resource Types: file file { ‘/etc/ssh/sshd_config’: ensure => file, owner => root, group => root, mode => ‘0644’, } ensure: § file – make sure it’s a normal file § directory – makes sure it is a directory (enables recursive) § link – ensures file is a symlink (requires target attribute) § absent – deletes file if it exists

Common Resource Types: file attributes
Attributes:
§ source
§ content
§ target

Common Resource Types: package
package { ‘tree’:
ensure => present
}
Installing packages with an array (multiple packages at one time)
package { [‘tree’,’bind-utils’]:
ensure => present,
}

Common Resource Types: service
service { ‘sshd’:
ensure => running,
enable => true,
}
Ensure: stopped/running
Enable: determines if a service should be enabled to start at boot time. Values: true/false

Case statements
case $osfamily {
‘RedHat’: { $ssh_name = ‘sshd’ }
‘Debian’: { $ssh_name = ‘ssh’ }
‘default’: { Warning(‘OS family does not match‘) }
}
service { ‘resource-name’:
name => $ssh_name
ensure => running,
enable => true,
}

###################################################################

[root@docker manifests]# vim init.pp
class ssh {
class {‘ssh::install’: }->
class {‘ssh::install’: }
}
[root@docker manifests]# puppet parser validate init.pp

[root@docker manifests]# vim install.pp
lass ssh::install{
package{‘openssh-server’:
ensure => present
}
}
[root@docker manifests]# vim service.pp
class ssh::service{
service{‘sshd’:
ensure => running,
enable => true,
hasstatus => true,
hasrestart => true
}
}

[root@docker manifests]# cd
[root@docker ~]# puppet module build rafi494-ssh/
Notice: Building /root/rafi494-ssh for release
Module built: /root/rafi494-ssh/pkg/rafi494-ssh-0.1.0.tar.gz

[root@docker ~]# puppet module list
/etc/puppet/modules (no modules installed)
/usr/share/puppet/modules (no modules installed)

[root@docker ~]# puppet module install rafi494-ssh/pkg/ –ignore-dependencies
[root@docker rafi494-ssh]# git commit -a
[master d478197] added ssh code
Committer: root <root@docker.c.rising-artifact-164906.internal>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

git config –global user.name “Your Name”
git config –global user.email you@example.com

After doing this, you may fix the identity used for this commit with:

git commit –amend –reset-author

2 files changed, 4 insertions(+), 42 deletions(-)
rewrite manifests/init.pp (98%)

[root@docker rafi494-ssh]# git push
Counting objects: 9, done.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (5/5), 423 bytes | 0 bytes/s, done.
Total 5 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
To git@github.com:rafi494/puppet-ssh.git
1e96716..d478197 master -> master

[root@docker rafi494-ssh]# git commit -a
# On branch master
# Untracked files:
# (use “git add …” to include in what will be committed)
#
# manifests/install.pp
# manifests/service.pp
# pkg/
nothing added to commit but untracked files present (use “git add” to track)
[root@docker rafi494-ssh]# git add manifests/install.pp
[root@docker rafi494-ssh]# git add manifests/service.pp
[root@docker rafi494-ssh]# git commit -a
[master 47816f8] install and service manifests
Committer: root <root@docker.c.rising-artifact-164906.internal>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

git config –global user.name “Your Name”
git config –global user.email you@example.com

After doing this, you may fix the identity used for this commit with:

git commit –amend –reset-author

2 files changed, 14 insertions(+)
create mode 100644 manifests/install.pp
create mode 100644 manifests/service.pp

[root@docker rafi494-ssh]# git push
Counting objects: 7, done.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 558 bytes | 0 bytes/s, done.
Total 5 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To git@github.com:rafi494/puppet-ssh.git
d478197..47816f8 master -> master

git.png

#########################################################################

Facts

[root@docker rafi494-ssh]# vim params.pp
class ssh::params {
case $::osfamily{
‘Debian’: {
$package_name = ‘openssh-server’
$service_name = ‘ssh’
}
‘RedHat’: {
$package_name = ‘openssh-server’
$service_name = ‘sshd’
}
default:{
fail(“${facts[‘operatingsystem’]}is not supported!”)
}
}
}
[root@docker rafi494-ssh]# vim init.pp
class ssh(
String $package_name = $::ssh::params::package_name,
String $service_name = $::ssh::params::service_name,
) inherits ::ssh::params {
class {‘::ssh::install’: }->
class {‘::ssh::service’}
}
[root@docker rafi494-ssh]# vim install.pp
class ssh::install(
String $package_name = $::ssh::package_name
) {
package {‘ssh-package’:
ensure => present,
name => $package_name,
}
}

[root@docker rafi494-ssh]# vim service.pp
class ssh::service(
String $service_name = $::ssh::params::service_name ,
){
service {‘ssh-service’:
ensure => running,
enable => true,
hasstatus => true,
name => $service_name
}
}

#########################################################

writing custom parameters 

cd /etc/puppet/modules/ssh

mkdir files
cp /etc/ssh/sshd_config files

mkdir templates
cp files/sshd_config templates
mv templates/sshd_config templates/sshd_config.erb

vim templates/sshd_config.erb
<% if @permit_root_login %>
PermitRootLogin yes
<% end %>

vim manifests/params.pp
$permit_root_login = false

vim init.pp
Boolean permit_root_login = $::ssh::params::permit_root_login,

vim config.pp
class ssh::config (
$permit_root_login = $::ssh::params::permit_root_login,
) {
….
….
….
content => templates(‘ssh::sshd_config.erb’)
}
##########  EX-2 #################

vim templates/sshd_config.erb
port <% @port %>

vim manifests/params.pp
$port = 22,

vim init.pp
Integer port = $::ssh::params::port’

vim config.pp
$port = $::ssh::params::port,

######################################################

[root@ansible ~]# vim notify.pp
notify { “hai this from test “: }

[root@ansible ~]# puppet apply notify.pp
Notice: Compiled catalog for ansible.localdomain in environment production in 0.02 seconds
Notice: hai this from test
Notice: /Stage[main]/Main/Notify[hai this from test ]/message: defined ‘message’ as ‘hai this from test ‘
Notice: Finished catalog run in 0.01 seconds

[root@ansible ~]# vim test_data_type.pp
$test_var = “some data”
case $test_var {
Hash: {
notify { “this var is a hash!”: }
}
String: {
notify { “this var is a string”: }
}
default: {
notify { “var not in list”: }
}
}
[root@ansible ~]# puppet apply test_data_type.pp
Notice: Compiled catalog for ansible.localdomain in environment production in 0.02 seconds
Notice: var not in list
Notice: /Stage[main]/Main/Notify[var not in list]/message: defined ‘message’ as ‘var not in list’
Notice: Finished catalog run in 0.04 seconds

#######################################################

Puppet Functions

[root@ansible ~]# vim create_resource.pp
$users = {
‘jack’ => {
home => ‘/home/jack’,
},
‘jones’ => {
home => ‘/home/jones’
},
‘tom’ => {
home => ‘/home/tom’,
},
‘smith’ => {
home => ‘/home/smith’
}
}
$defaults = {
‘ensure’ => ‘present’,
managehome => true,
gid => ‘admin’,
shell => ‘/bin/bash’,
require => Group[‘admin’]
}

group {‘admin’:
ensure => present
}
create_resources(user,$users,$defaults)
[root@ansible ~]# puppet apply create_resource.pp
Notice: Compiled catalog for ansible.localdomain in environment production in 0.38 seconds
Notice: /Stage[main]/Main/Group[admin]/ensure: created
Notice: /Stage[main]/Main/User[smith]/ensure: created
Notice: /Stage[main]/Main/User[jack]/ensure: created
Notice: /Stage[main]/Main/User[jones]/ensure: created
Notice: /Stage[main]/Main/User[tom]/ensure: created
Notice: Finished catalog run in 0.31 seconds

[root@ansible ~]# tail -4 /etc/passwd
smith:x:1002:1002::/home/smith:/bin/bash
jack:x:1003:1002::/home/jack:/bin/bash
jones:x:1004:1002::/home/jones:/bin/bash
tom:x:1005:1002::/home/tom:/bin/bash

Iteration and loops

#########################################
[root@ansible ~]# vim iteration.pp
$values = [‘a’,’b’,’c’,’d’,’e’]
$values.each | String $value | {
notify { $value:
message =>”Value from a lambda code block: ${value}”
}
}
#########################################
[root@ansible ~]# vim each.pp
$facts[‘os’].each |$values| {
notify { $values[0]
message => $values[1],
}
}
#########################################
[root@ansible ~]# vim slice.pp
notice $facts[‘os’]
$facts[‘os’].slice(2) |$value,| {
notice “Value: ${value}”
}
#########################################
[root@ansible ~]# vim slice2.pp
notice $facts[‘os’]
$facts[‘os’].slice(2) |$value1, $value2| {
notice “Value1: ${value1}, Value2: ${value2}”
}
#########################################
[root@ansible ~]# vim reduce.pp
$hash = {a =>1, b=>2, c=>3}

$results = $hash.reduce |$memo, $value| {
notice “String: memo: ${memo[0]}, ${value:[0]}”
$string = “${memo[o]}${value[o]}”
notice “Number: memo: ${memo[1]}, ${value:[1]}”
$num = $memo[1] + $value[1]
}

notice $results
################    Defined Functions ###########################

[root@ansible ~]# vim show_message.pp
define show_message(
String $message,
){
notify { $title:
message => message,
}
}

$messages = {
‘message1’ => { ‘message’ => ‘this is message 1’ },
‘message2’ => { ‘message’ => ‘this is message 2’ },
}

create_resources(show_message, $messages)

##########################################

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s