fundamentals puppet

327
Puppet Fundamentals for System Administrators Student Guide Puppet Education www.puppetlabs.com/learn Puppet Fundamentals Fundamentals v3.4.9 1 ©2015 Puppet Labs

Upload: victor-martinez

Post on 17-Jul-2016

188 views

Category:

Documents


2 download

DESCRIPTION

Fundamentals Puppet

TRANSCRIPT

Page 1: Fundamentals Puppet

PuppetFundamentals

forSystemAdministrators

StudentGuide

PuppetEducationwww.puppetlabs.com/learn

PuppetFundamentals

Fundamentalsv3.4.9 1 ©2015PuppetLabs

Page 2: Fundamentals Puppet

Training&CertificationPuppetFundamentalsisthecertificationcurriculumforthePuppetProfessionalCertification.

FormoreinformationaboutPuppetEducation&Training,pleasevisit:http://puppetlabs.com/learn.

FormoreinformationaboutthePuppetCertificationProgram,pleasevisit:http://puppetlabs.com/certification.

Training&Certification

Fundamentalsv3.4.9 2 ©2015PuppetLabs

Page 3: Fundamentals Puppet

TableofContentsAboutPuppetPuppetComponentRolesInstallPuppetEnterpriseClassroomEnvironmentBasicPuppetConceptsModulesandClassesClassificationResourcesResourceRelationshipsLanguageConstructsERBTemplatesDefinedResourceTypesAdvancedClassesPuppetForgeIntroductiontoRoles&ProfilesCapstoneLabCourseConclusionAppendix:ReferencesAppendix:LiveManagementAppendix:Resources

TableofContents

Fundamentalsv3.4.9 3 ©2015PuppetLabs

Page 4: Fundamentals Puppet

PuppetFundamentalsPuppetFundamentalsteachesthebasicPuppetconceptsrequiredforamemberofanOperationsteamusingPuppetforconfigurationmanagement.

LearningObjectives:

DemonstratetheusageoffundamentalPuppetlanguageconstructs.Discoverandusemanycoreresourcetypes.Describethecorepreceptsofastatemodelinglanguage.DescribePuppet'splatformabstractioncapabilities.Writecodemakinguseofstatemodelingandplatformabstractionprinciples.

PuppetFundamentals

Fundamentalsv3.4.9 4 ©2015PuppetLabs

Page 5: Fundamentals Puppet

CourseOverview

Youwill:Developmodules/classesonasystemthatrepresentsyourtargetsystem.Usepuppet applytotestanditerateonthatmodule.PlacethatmoduleonyourPuppetMaster.Declaretheappropriateclassinyournodedefinition.CollectandanalyzeresultsintheEnterpriseConsole.

CourseOverview

Fundamentalsv3.4.9 5 ©2015PuppetLabs

Page 6: Fundamentals Puppet

CourseAgenda

Day1AboutPuppetandPuppetLabsSettinguptheclassroomenvironmentLearningthePuppetcomponentrolesUnderlyingPuppetconceptsDesigningmodulesandclasses

CourseAgenda

Fundamentalsv3.4.9 6 ©2015PuppetLabs

Page 7: Fundamentals Puppet

CourseAgenda

Day2ClassificationResourcesResourceRelationshipsLanguageConstructsTemplatesDefinedResources

CourseAgenda

Fundamentalsv3.4.9 7 ©2015PuppetLabs

Page 8: Fundamentals Puppet

CourseAgenda

Day3AdvancedClassesPuppetForgeRolesandProfilesCapstoneLabCourseConclusion

CourseAgenda

Fundamentalsv3.4.9 8 ©2015PuppetLabs

Page 9: Fundamentals Puppet

MakingAcquaintances

Helpmetailortheclassroomexperiencetowardsyourneeds.

HowlonghavehaveyoubeenusingPuppet?Whatrolesdoyouserveatwork?

TechnicalSupportSysadminDBAdminDeveloperManagement

Whichoperatingsystemsdoyouhaveexperiencewith?LinuxMacOSXSolarisWindows

Vi(m)orEmacs?HaveyouusedPuppetEnterprise? Yes NoDoyoufeelpreparedforthisclass? Yes No

MakingAcquaintances

Fundamentalsv3.4.9 9 ©2015PuppetLabs

Page 10: Fundamentals Puppet

AboutPuppet

AboutPuppet

Fundamentalsv3.4.9 10 ©2015PuppetLabs

Page 11: Fundamentals Puppet

Overview:AboutPuppet

Objectives

Attheendofthislesson,youwillbeableto:

Identifythechallengesofinfrastructuremanagement.ExplainhowbothPuppetandPuppetEnterprisecanbeusedtoovercomesuchchallenges.DescribePuppetLabs'approachtoconfigurationmanagement.

Overview:AboutPuppet

Fundamentalsv3.4.9 11 ©2015PuppetLabs

Page 12: Fundamentals Puppet

AboutPuppetLabs

Notes:

activemailinglists

[email protected]@googlegroups.com

IRCchannels,includingcommunityandPuppetemployees

#puppetonfreenode.net#puppet-devonfreenode.net

AboutPuppetLabs

Fundamentalsv3.4.9 12 ©2015PuppetLabs

Page 13: Fundamentals Puppet

LegacyAutomation

Notes:

Legacyautomationtechniqueshortcomingsinclude:ManuallyConfigure(literallyloggingintoeverynodetoconfigureit)

DifficulttoscaleRealisticallyimpossibletomaintainconsistencybetweennodes

GoldenImages(Usingacompletetemplatetocreatenewnodeinstallations)

Needseparateimagesfordifferentenvironments,configurations,orroles.Verydifficulttomaintainconsistencyacrossmultipleimageversions.Monolithicimagesarerigidanddifficulttoupdateasthebusinessneedschange

continued...

LegacyAutomation

Fundamentalsv3.4.9 13 ©2015PuppetLabs

Page 14: Fundamentals Puppet

CustomOne-offScripts(customcodewrittentoaddressaspecific,tacticalproblem)

DifficulttoreusefordifferentapplicationsordifferentdeploymentsBrittle;asneedschange,theentirescriptmustoftenbere-writtenDifficulttomaintainwhentheoriginalauthorleavestheorganizationOftenlessreliable,asscriptsareusedandtestedonlybyyourorganizationandnotbyacompletecommunity.

SoftwarePackages(typicallyallornothingapproach)

Typicallyrequirethatallresourcesbeplacedundermanagement.Userscannotselectivelyadoptandscaleautomationandasaresult,deploymenttimesaremuchlongerandmorelaborintensive.DatedtechnologydevelopedbeforevirtualizationandcloudcomputingandoftenlacksresponsivenesstochangingrequirementsOftenbackedbyadatabasewithsomesortof"composer"graphicalfrontend.BackinguporreplicatingconfigurationoftenrequiresintimatedatabaseandschemaknowledgeinsteadoftheeaseofworkingwithPuppet'sflatfilemanifests.

AninterestingtooltohelpyourorganizationevaluateyourownperformanceistheOperationsReportCard,locatedathttp://www.opsreportcard.com

LegacyAutomation

Fundamentalsv3.4.9 14 ©2015PuppetLabs

Page 15: Fundamentals Puppet

IntroducingPuppetEnterprise

ConfigurationManagementforsystemsadministrators.

Notes:

InsightDoyouhavetosiftthroughlogfilesanduseadhocscriptstounderstandchangesinyourinfrastructure?PuppetEnterprise'seventinspectorgivesimmediateandactionableinsightintoyourenvironment,showingyouwhatchanged,whereandhowbyclasses,nodesandresources.

DiscoveryDoyouhesitatetoturnoffaserverbecauseyou'renotsurewhat'sonit?PuppetEnterprisedeliversadynamicandfully-pluggablediscoveryservicethatallowsyoutoquicklylocate,identifyandgroupcloudnodes.

ProvisioningAutomaticallyprovisionandconfigurebaremetalorvirtualmachinesusingPuppetLabs'allnewRazorrulesbasedprovisioningengine.SetyourinfrastructuretoPXEbootfromtheRazorserver,writeafewrulesandprovisionwithease.

continued...

IntroducingPuppetEnterprise

Fundamentalsv3.4.9 15 ©2015PuppetLabs

Page 16: Fundamentals Puppet

ConfigurationManagementPuppetEnterprise'sdeclarative,model-basedapproachautomatesrepetitivetasksandeliminatesconfigurationdrift.Youdefinethedesiredstateofyourinfrastructure,andPuppetEnterpriseenforcesthisstate,freeingyoutoworkontougherprojects.

OrchestrationUsethecommandlinetoquicklydeploycriticalupdates,likesecuritypatches,acrosshundredsofserversinseconds,orproactivelyinitiatePuppetrunstoupdateconfigurationsandreportchanges.PuppetEnterpriseallowsyoutoorchestratecontrolled,multi-stepoperationstotargetedcollectionsofnodes,givingyoucompletecontroloverinfrastructurechanges.

ReportingGetvisibilityintoyourinfrastructure,browseresources,andviewreportsthathelpyoumanageyourconfiguration.PuppetEnterpriseprovidesnodehardwareandsoftwareinventory,Puppetrunchangereports,andnodeconfigurationgraphsviatheproduct'sconsoleor3rdpartyAPIs.

IntroducingPuppetEnterprise

Fundamentalsv3.4.9 16 ©2015PuppetLabs

Page 17: Fundamentals Puppet

PuppetEnterpriseStack

Simplifiesinstallationandconfiguration.FullyintegratedandtestedPEstack:

JVMPuppetMasterPuppetAgentPuppetEnterpriseConsoleNodeClassifierEventInspectorPuppetServerMetrics

Automaticallyconfiguredtoscale.Enterprisesupportisincluded.

PuppetEnterpriseStack

Fundamentalsv3.4.9 17 ©2015PuppetLabs

Page 18: Fundamentals Puppet

ModelBasedApproach

DescribeyourdesiredstateandletPuppetenforceit

Notes:

1. Describeyourinfrastructureanditsdesiredstate.

UsePuppettodescribetheattributesofresources.Manageasmuchoraslittleasyou'dlikeandprogressivelyrolloutconfigurationmanagement.

2. Simulatetheenforcementoftheseresourcedefinitions

Simulateconfigurationchangessoyoucanunderstandtheimpactofchangesbeforeputtingthemintoproduction

3. Enforcethedesiredstateofyourinfrastructure

Periodicallybringeachnodeintocompliancewiththesedefinitionsandmaintaininfrastructure-wideconfigurationconsistency.

4. Reportonthestateofyourinfrastructure

ViewruntimereportsfromeachAgentorbrowsecomprehensivelyaggregatedresourcechangesacrossallnodestoachievecompletevisibility.

ModelBasedApproach

Fundamentalsv3.4.9 18 ©2015PuppetLabs

Page 19: Fundamentals Puppet

ComposableConfigurations

Buildconfigurationmodelsfromsmallercomponents

Notes:

Puppet'shuman-readableDSLenablesyoutospecifyandmanageyourinfrastructurewithdefinedmodelsofyourinfrastructure,notprocedures.Completeservicesandapplications--webservers,databaseservers,applicationservices--canbebuiltfromcollectionsofmodulesorre-usable"buildingblock"components.Becausethesemodelsarecentrallymanaged,youcanmakechangesonce,testthem,andthendeployconsistentconfigurationstomultiplenodes.Puppet'sresourceabstractionlayerenablesre-usableandportableconfigurationsacrossanysupportedplatform.

Tohelpusersgetstarted,PuppetLabshasthousandsoffreelydownloadablemodulesforresources,applications,andservicesattheForgecommunitysite:http://forge.puppetlabs.com.

ComposableConfigurations

Fundamentalsv3.4.9 19 ©2015PuppetLabs

Page 20: Fundamentals Puppet

LifecycleofaPuppetAgentRun

DataFlowBetweenPuppetComponents

Notes:

AlookathowdefinitionsareusedtoautomaticallyconfigureandmanageITinfrastructure:

1. ThePuppetAgentonthenodetellsthePuppetMasterinformationaboutitself(hostname,nodename,operatingsystem,etc.).

2. ThePuppetMasterlooksuptheconfigurationforthatnodeandsendsaCatalogrepresentingthatintendedconfigurationbacktothenode.

3. Thenodereportsbackanyactionsthatweretakentoenforcethatconfiguration.

4. ThePuppetMasterserveraggregatesallthereportsfromallthenodesandprovidesasingleoverviewonthestateofyourinfrastructure.

LifecycleofaPuppetAgentRun

Fundamentalsv3.4.9 20 ©2015PuppetLabs

Page 21: Fundamentals Puppet

PuppetComponentRoles

PuppetComponentRoles

Fundamentalsv3.4.9 21 ©2015PuppetLabs

Page 22: Fundamentals Puppet

Lesson2:PuppetComponentRoles

Objectives

Attheendofthislesson,youwillbeableto:

DescribetherolesoftheAgentandtheMaster.Classifyanodewithdesiredconfigurations.UsethereportingfeaturesofthePuppetEnterpriseconsole.RunthePuppetAgentfromthecommandline.

Lesson2:PuppetComponentRoles

Fundamentalsv3.4.9 22 ©2015PuppetLabs

Page 23: Fundamentals Puppet

PuppetConfigurationManagement

PuppetConfigurationManagement

Fundamentalsv3.4.9 23 ©2015PuppetLabs

Page 24: Fundamentals Puppet

TheMasterService

puppet masterrunsonthecentralserver.Itisresponsiblefor:

authenticatingagentconnections.signingcertificates.servingacompiledcatalogtotheagent.servingfiles.processingpostedreports.

DoesnotrunonAIX,OSX,Solaris,orWindowsRunsontheJVMforincreasedperformanceatscale.

TheMasterService

Fundamentalsv3.4.9 24 ©2015PuppetLabs

Page 25: Fundamentals Puppet

ThePuppetMasterRoleInamonolithicinstallthePuppetMasterwill:

CompileandserveconfigurationcatalogstoPuppetAgentnodes.IssueMCollectivecommandsandrouteMCollectivemessages.ServethePuppetEnterpriseConsolewebinterface.Collectreportsfromnodesandservenodeinformation.

Inthisclass,theclassroommasterwillalso:

Providesourcecontrolrepositoriesforeachstudent.

ThePuppetMasterRole

Fundamentalsv3.4.9 25 ©2015PuppetLabs

Page 26: Fundamentals Puppet

Demo

InstallingPuppetMaster

Notes:

Donotfollowalongwiththeinstructor,asyouwillbeinstallingonlytheAgentonyourownnode.IfyouinstallthePuppetMasteroutsideofthisclassroomyoushouldfollowthedirectionsathttp://docs.puppetlabs.com/pe/latest/install_basic.html.

ThevirtualmachineusedinclassisabaseCentOSinstallminimallymodifiedtoallowforclassroomusewithoutnetworkaccess.

PuppetEnterpriseisdownloadedandavailableforinstallation.Syntaxhighlightingforcommoneditorsisavailable.Themodulesrequiredfortheclassarecachedlocally.Somesystempackagesrequiredforthecoursearealsocachedinalocalyumrepository.

Demo

Fundamentalsv3.4.9 26 ©2015PuppetLabs

Page 27: Fundamentals Puppet

TheAgentService

puppet agentrunsonallmanagednodes.Itisresponsiblefor:

requestingconfigurationstatefromthePuppetMaster.sendinginformationaboutitscurrentstate(facts).enforcingaretrievedconfigurationstate(catalog).

Agentsupportedplatformsinclude:

Linux(RHEL,Debian,andseveralotherdistributions)WindowsSolarisMacOSXAIXNetworkDevices(AristaEOS,Cumulus)

Notes:

Thecatalogisanobjectthatrepresentsthedesiredend-stateofanode.

ThePuppetEnterprisesupportedplatformscanbefoundathttp://puppetlabs.com/puppet/requirements

Otherpointstonote:AllcommunicationsbetweentheMasterandAgentaresecuredandauthenticatedviaSSL.TheAgentperformsseveralotherancillaryfunctions:

SynchronizingandPuppetextensionsfromtheMaster.RetrievingsupportfilesasneededfromtheMaster.SendingareportbacktotheMaster.etc.

TheAgentService

Fundamentalsv3.4.9 27 ©2015PuppetLabs

Page 28: Fundamentals Puppet

UsefulCommandLineArguments--test

--no-daemonize

--verbose

--onetime

...

--noop

--debug

--environment <env>

--configprint <config option>

Notes:

Thecompletelistofoptionsimpliedby--testare:--test

--no-daemonize--verbose--onetime--ignorecache--no-usecacheonfailure--detailed-exitcodes--show_diff--no-splay

continued...

UsefulCommandLineArguments

Fundamentalsv3.4.9 28 ©2015PuppetLabs

Page 29: Fundamentals Puppet

Otheroptionsthatmightbeinteresting--tags <tags>

Conditionallyapplypartsofthecatalogbasedontags

--genconfig

Generateastartingconfigfile.MostlyusefulforOpenSourceuserssettinguptheirinfrastructureforthefirsttime.

--trace

Generatefullstacktracesonerrors,whichcanbeusefulfordebugging.

--waitforcert

Howlongtheagentshouldwaitforitscertificatetobesignedbeforegivingup.Usefulduringagentprovisioning.

Fullconfigurationoptionreferencecanbefoundathttps://docs.puppetlabs.com/references/latest/configuration.html.Alloptionscanbespecifiedeitherintheconfigfileoronthecommandline.

UsefulCommandLineArguments

Fundamentalsv3.4.9 29 ©2015PuppetLabs

Page 30: Fundamentals Puppet

ExampleConfiguration[main]

certname = master.puppetlabs.vm

vardir = /var/opt/lib/pe-puppet

logdir = /var/log/pe-puppet

rundir = /var/run/pe-puppet

basemodulepath = /etc/puppetlabs/puppet/modules:/opt/puppet/share/puppet/modules

environmentpath = /etc/puppetlabs/puppet/environments

server = master.puppetlabs.vm

user = pe-puppet

group = pe-puppet

archive_files = true

archive_file_server = master.puppetlabs.vm

module_groups = base+pe_only

dns_alt_names = puppet

environment_timeout = 0

[agent]

report = true

classfile = $vardir/classes.txt

localconfig = $vardir/localconfig

graph = true

pluginsync = true

environment = production

[master]

node_terminus = classifier

ca_server = master.puppetlabs.vm

reports = console,puppetdb

storeconfigs = true

storeconfigs_backend = puppetdb

certname = master.puppetlabs.vm

server = master.puppetlabs.vm

always_cache_features = true

Notes:

Eachsectioncorrespondstoarunmode.The[main]sectionwillapplytoallrunmodes,but[master],[agent],and[user]applyonlytothegivenrunmode.Assuch,yourAgentswillnothavea[master]section.Eachconfigurationsettinginpuppet.confalsohasacorrespondingsettingonthecommandline.Optionsareresolvedinthisorder:

command line > run mode > main > puppet defaults

continued...

ExampleConfiguration

Fundamentalsv3.4.9 30 ©2015PuppetLabs

Page 31: Fundamentals Puppet

Thismeansthatasettingin[agent]willoverrideasettingin[main]whenrunningpuppetagent -t,butthatanoptionspecifiedonthecommandlineoverridesboth.

Otherconfigurationvariablesofinterest:vardir:locationwherePuppetstoresdynamicallygrowinginformation.rundir:locationwherePuppetPIDfilesarestored.ssldir:locationwhereSSLcertificatesarestored.ca_server:theservertouseforcertificateauthorityrequests.certname:thecertificatenametousewhencommunicatingwiththemaster.server:thehostnameofthepuppetmaster.

OnaLinuxandmostUnixsystems,thepuppet.conffiledefaultsto:PuppetEnterprise:/etc/puppetlabs/puppet/puppet.confPuppetOpenSource:/etc/puppet/puppet.conf

OnMicrosoftWindowssystems,thepuppet.conffiledefaultstoeither:C:\ProgramData\PuppetLabs\etc\puppet.confC:\Documents and Settings\All Users\ApplicationData\PuppetLabs\etc\puppet.conf

ExampleConfiguration

Fundamentalsv3.4.9 31 ©2015PuppetLabs

Page 32: Fundamentals Puppet

Agent/MasterArchitecture

Notes:

TheonlyinformationtransmittedbetweentheMasterandAgentistheFactssubmittedbytheAgentandtheCatalogreturnedbytheMaster.ThismeansthattheMasterhasnoinherentknowledgeofanyotherstateontheAgentandtheAgentseesnoneofthePuppetsourcecodeusedtogeneratethecatalog.

Theconceptsreferencedinthislifecyclediagramwillbeexplainedinmoredetaillaterinthecourse.

Agent/MasterArchitecture

Fundamentalsv3.4.9 32 ©2015PuppetLabs

Page 33: Fundamentals Puppet

PuppetEnterpriseConsole

GraphicalinterfacetothePuppetinfrastructure.

Itisresponsiblefor:

presentinganoverviewofyoursystems.providingdetailedinformationabouteachnode.collatinganddisplayingstatistics.providinganinterfacefornodeclassification.enablingreportbrowsingandviewing.

PuppetEnterpriseConsole

Fundamentalsv3.4.9 33 ©2015PuppetLabs

Page 34: Fundamentals Puppet

Demo

ConfiguringtheclassroomPuppetMaster

Demo

Fundamentalsv3.4.9 34 ©2015PuppetLabs

Page 35: Fundamentals Puppet

InfrastructureOverview

InfrastructureOverview

Fundamentalsv3.4.9 35 ©2015PuppetLabs

Page 36: Fundamentals Puppet

NodeDetailsandStatistics

NodeDetailsandStatistics

Fundamentalsv3.4.9 36 ©2015PuppetLabs

Page 37: Fundamentals Puppet

ClassifyingaNodeGroup

Notes:

NodegroupsarethecoreoftheNodeClassifier.Thisreplacestheoldpracticeofone-offnodeconfigurationswithasetofrulesidentifyingtheclassificationthatshouldbeappliedtoeachnode.

ClassifyingaNodeGroup

Fundamentalsv3.4.9 37 ©2015PuppetLabs

Page 38: Fundamentals Puppet

BrowsingLatestReports

BrowsingLatestReports

Fundamentalsv3.4.9 38 ©2015PuppetLabs

Page 39: Fundamentals Puppet

ViewingaReport

ViewingaReport

Fundamentalsv3.4.9 39 ©2015PuppetLabs

Page 40: Fundamentals Puppet

Checkpoint:ComponentRoles

WhatdothepartsofPuppetEnterprisedo?

ThePuppetAgentcompilesacatalog.TrueFalse

WhatinformationdoestheMasterhaveabouttheAgent?FactsgatheredbytheagentThelistofpackagesinstalledontheagentHomedirectoriesofnon-systemusersAlistoftheprovidersontheagent

ThemachinerunningthePuppetMastertypicallyalsorunstheAgent.TrueFalse

ThePuppetEnterpriseConsoleallowstheuserto:DefinerulestoclassifynodesSeewhichnodesarecurrentlyapplyingacatalogSeeaquickoverviewofyourinfrastructureBrowsereportsandviewresultsofindividualagentrunsLookbusywhenthebosswalksby

Checkpoint:ComponentRoles

Fundamentalsv3.4.9 40 ©2015PuppetLabs

Page 41: Fundamentals Puppet

InstallPuppetEnterprise

InstallPuppetEnterprise

Fundamentalsv3.4.9 41 ©2015PuppetLabs

Page 42: Fundamentals Puppet

Lesson3:InstallPuppetEnterprise

Objectives

Attheendofthislesson,youwillbeableto:

SetupalocalPuppetAgentandconnectittotheclassroomPuppetMaster.Usefactertodisplaysystemfactsforyournode.ExplaintheconceptsbehindPuppetresources.Usepuppet resourcetoinspectlocalresources.

Lesson3:InstallPuppetEnterprise

Fundamentalsv3.4.9 42 ©2015PuppetLabs

Page 43: Fundamentals Puppet

Demo

InstallingthePuppetAgent

Notes:

Donotfollowalongwiththeinstructor,asyouwillbeinstallingtheAgentonyourownnodeinjustamoment.

Demo

Fundamentalsv3.4.9 43 ©2015PuppetLabs

Page 44: Fundamentals Puppet

Lab3.1:Installation

Objective:

InstallthePuppetAgentonyourvirtualmachineandexploresomeofthebasicfunctionalityofPuppetEnterprise.

Notes:

ThiscourseusesPuppetEnterpriseforalllabsandexercises,soweareinstallingtheEnterpriseversionofourSoftwareatthispoint.However,theprinciplesandconceptstaughtinthiscourseapplyequallytoPuppetOpenSource,unlessspecificallydesignatedasPuppetEnterpriseonlyinthecoursematerials.

ForfurtherdocumentationoninstallingPuppetEnterprise,seehttp://docs.puppetlabs.com/pe/latest/install_basic.html.

Lab3.1:Installation

Fundamentalsv3.4.9 44 ©2015PuppetLabs

Page 45: Fundamentals Puppet

FacterPuppetusesfactertogatherinformationaboutthehostsystem.Executingthefactercommandreturnsalistofkeyvaluepairs.

[root@training ~]# facter

architecture => x86_64

domain => puppetlabs.com

facterversion => 1.5.2

fqdn => training.puppetlabs.lan

hardwaremodel => x86_64

hostname => training

interfaces => eth0

ipaddress => 172.16.10.1

kernel => Linux

operatingsystem => Ubuntu

...

Thereturnedkeyvaluepairsarefacts.

Notes:

FacterisPuppet'ssysteminventorytool.Facterdiscoversfactsintrinsictoanode(suchasitshostname,networkinterfacesandIPaddresses,operatingsystem,etc.)andmakesthemavailabletoPuppet.Facterincludesalargenumberofbuilt-infacts.Youcanviewtheirnamesandvaluesforthelocalsystembyrunningfacteratthecommandline.Inagent/masterPuppetarrangements,agentnodessendtheirfactstothemaster,andthemastercompilesthecatalogusingthesefacts.

FactsarealwaysgeneratedpriortotheAgentrun.YoucannotchangefactsduringcompilationandyourcatalogcannotusefactstomakeconditionaldecisionsontheAgentduringapplication.Wewilltalklaterabouthowtouseconditionalstochangehowthecatalogisbuilt.

NewerversionsofPuppetEnterpriseenablestructuredfacts,meaningthatsomefactswillreturnarrayorhashdataobjectsinsteadofjustsimplestrings.

Facter

Fundamentalsv3.4.9 45 ©2015PuppetLabs

Page 46: Fundamentals Puppet

Exercise3.2:Facter

Objective:

Becomefamiliarwiththeuseoffacter.Observetheoutputofsomecommonfacts.Comparefactvalueswithothersintheclassroom.

Exercise3.2:Facter

Fundamentalsv3.4.9 46 ©2015PuppetLabs

Page 47: Fundamentals Puppet

PuppetResourceAcommandlinetoolforinspectingPuppetresourcesonthesystem.ItinteractsdirectlywiththeResourceAbstractionLayer(RAL).ReturnsthePuppetcoderepresentationofthecurrentstateofaresource.

PuppetResource

Fundamentalsv3.4.9 47 ©2015PuppetLabs

Page 48: Fundamentals Puppet

PuppetResourceQuery

UsetheRALtoretrievethestateofaresourceThepuppet resourcecommandtakestwoarguments

1. <resource type>2. <resource title>

Returnsthecurrentstateofaresource.

[root@training ~]# puppet resource user elvis

user { 'elvis':

ensure => absent,

}

PuppetResourceQuery

Fundamentalsv3.4.9 48 ©2015PuppetLabs

Page 49: Fundamentals Puppet

PuppetResourceQuery

UsetheRALtoretrievethestateofmanyresourcesExecutingthepuppet resourcecommandwithonly

1. <resource type>Returnsthecurrentstateofallresourcesofagiventype.

[root@training ~]# puppet resource user

....

user { 'vcsa':

ensure => present,

uid => '69',

gid => '69',

shell => '/sbin/nologin',

comment => 'virtual console memory owner',

home => '/dev',

}

user { 'willywonka':

ensure => present,

uid => '1006',

gid => '1008',

shell => '/bin/bash',

home => '/home/willywonka',

}

Notes:

Resourcesthatareenumerable,orhaveafinitenumberofinstancesonanode,canbelistedwithpuppet resource.Hostrecordscan,becausethere'safinitelistin/etc/hosts.Execresourcescannotbelistedthiswaybecausethere'snowaytolistallpossibleexecstatements.

PuppetResourceQuery

Fundamentalsv3.4.9 49 ©2015PuppetLabs

Page 50: Fundamentals Puppet

Exercise3.3:PuppetResource

Objective:

Usepuppet resourcetoinspectuseraccounts.Observeresourcechangesinaction.

Exercise3.3:PuppetResource

Fundamentalsv3.4.9 50 ©2015PuppetLabs

Page 51: Fundamentals Puppet

Checkpoint:Installation

FirstinteractionswiththePuppettoolchain

RunningpuppetresourceinstructsPuppettobeginmanagingthatresource.TrueFalse

Runningpuppetresourcecantellyouwhatpropertiesofaresourcecanbemanaged.TrueFalse

FactscanchangeduringaPuppetrun.TrueFalse

Imisshavingtousethetextbasedinstallwizard.TrueFalse

Checkpoint:Installation

Fundamentalsv3.4.9 51 ©2015PuppetLabs

Page 52: Fundamentals Puppet

ClassroomEnvironment

ClassroomEnvironment

Fundamentalsv3.4.9 52 ©2015PuppetLabs

Page 53: Fundamentals Puppet

Lesson4:ClassroomEnvironment

Objectives

Attheendofthislesson,youwillbeableto:

SetupanenvironmentforyourowncodeonthePuppetMaster.UseabasicPuppetdevelopmentworkflowtoupdateyourenvironment.

Lesson4:ClassroomEnvironment

Fundamentalsv3.4.9 53 ©2015PuppetLabs

Page 54: Fundamentals Puppet

VersionControlWorkflow

Providesaframeworkfor:Safeandrecoverablechangesets.Seamlesscollaborationwithothers.Viewingcompletechangehistoryofcode.Backingoutproblematicchanges.

VersionControlWorkflow

Fundamentalsv3.4.9 54 ©2015PuppetLabs

Page 55: Fundamentals Puppet

VersionControlWorkflow

Process

1. Updatelocalworkingdirectory.

2. Editcodeandmakeanychangesrequired.

3. Validateandstylecheckcodelocally.

4. Testcodelocallybyapplyingtestmanifests.

5. UpdatePuppetMastermanifestrepository.

6. Testondevelopmentnodesinagentmode.

VersionControlWorkflow

Fundamentalsv3.4.9 55 ©2015PuppetLabs

Page 56: Fundamentals Puppet

TheClassroomEnvironment

TheClassroomEnvironment

Fundamentalsv3.4.9 56 ©2015PuppetLabs

Page 57: Fundamentals Puppet

Demo

CompletingtheClassroomEnvironment

Notes:

Theclassroomautomationtoolingdependsonfunctionalityfromthe.NETFramework4.5.IfyouseeanerrorrelatingtoGeoTrust_Global_CA.pem,thenyoushouldupgradeyour.NETinstallation.

http://www.microsoft.com/en-us/download/details.aspx?id=42643

Demo

Fundamentalsv3.4.9 57 ©2015PuppetLabs

Page 58: Fundamentals Puppet

gitMiniTutorialFreeandopensourcedistributedversioncontrolsystem.

UseGitonopenorproprietaryprojectsforfree,forever.Download,inspectandmodifythesourcecodetoGit.

Tinyfootprintwithlightningfastperformance:

nearlyalloperationsareperformedlocally.doesn'tconstantlycommunicatewithaserver.hugespeedadvantageovercentralizedsystems.

Cryptographicintegrityofeverybitofyourprojectisensured:

everyfileandcommitischecksummedandretrievedbyitschecksumwhencheckedbackout.assurancethatyourprojectisexactlythesameaswhenitwascommittedandthatnothinginitshistorywaschanged.

Notes:

Githasrapidlybecomeenormouslypopular.Itisusedforverymanyopensourceprojectsaswellasonenterpriselevelprojects.MicrosoftandApplehavebuiltgitsupportintotheirdevelopmenttools.GitHub.comprovidesfreehostedgitrepositories.Inshort,there'snoreasonnottolearnit!

gitMiniTutorial

Fundamentalsv3.4.9 58 ©2015PuppetLabs

Page 59: Fundamentals Puppet

git status

Tellsyouthestateofyourworkingdirectory.Runthiscommandoften,especiallybeforecommits.

Workingdirectorywithnochanges:

[root@training puppetcode]# git status

# On branch master

nothing to commit (working directory clean)

Afterchangeshavebeenmadetotheworkingdirectory:

[root@training puppetcode]# git status

# On branch master

#

# Initial commit

#

# Untracked files:

# (use "git add <file>..." to include in what will be committed)

#

# site.pp

nothing added to commit but untracked files present (use "git add" to track)

Notes:

Noticethatgitprovideshelpfulhintsastothesuggestednextactionyoumighttake.

gitstatus

Fundamentalsv3.4.9 59 ©2015PuppetLabs

Page 60: Fundamentals Puppet

git add

gitstagescodetobecommitted.Thisallowsyoutoiterativelybuildupacommit.Youcanaddfilesordirectoriesoneatatimeormanyatonce.Youchoosewhichchangesinyourworkingdirectorytocommit.

git add <file>addsafiletothestagingarea:

[root@training puppetcode]# git add site.pp

[root@training puppetcode]# git status

# On branch master

#

# Initial commit

#

# Changes to be committed:

# (use "git rm --cached <file>..." to unstage)

#

# new file: site.pp

#

gitadd

Fundamentalsv3.4.9 60 ©2015PuppetLabs

Page 61: Fundamentals Puppet

git commit

Commitsachangesettoyourrepository:afterallchangedfileshavebeenstagedwithgit add.takesacryptographically-verifiedsnapshotofyourstagedchanges.savesacheckpointintoyourrepository.specifyacommitmessageinoneoftwoways:

editmessageinyourdefaulteditor.maybepassedonthecommand-linewith-m.

git commitcommitschangestoyourrepository:

[root@training puppetcode]# git add site.pp

[root@training puppetcode]# git commit -m 'initial commit'

[master (root-commit) d798484] initial commit

1 files changed, 44 insertions(+), 0 deletions(-)

create mode 100644 site.pp

Notes:

TheeditoruseddefaultstotheprogramspecifiedbytheVISUALorEDITORenvironmentvariable.Itcanalsobeconfiguredbyrunninggit config --global core.editor .Forexample,

Linux:

git config --global core.editor /usr/bin/vim

Windows:

git config --global core.editor "'C:/ProgramFiles/Notepad++/notepad++.exe' -multiInst -notabbar -nosession-noPlugin"

gitcommit

Fundamentalsv3.4.9 61 ©2015PuppetLabs

Page 62: Fundamentals Puppet

Lab4.1:git commit

Objective:

Becomefamilarwiththeuseofgit status.Addandcommitcodetoyourrepository.

Lab4.1:gitcommit

Fundamentalsv3.4.9 62 ©2015PuppetLabs

Page 63: Fundamentals Puppet

DistributedVersionControlInsteadofcheckingoutthecurrentrevision,gitmakesafullcloneoftheentirerepository.Everyuseressentiallyhasafullbackupofthemainserver.

Nosinglepointoffailure

Allowsdisconnectedoperation;evencommitanddiffoperations.Withoutnetworkactivity,operationsareblindinglyfast.

DistributedVersionControl

Fundamentalsv3.4.9 63 ©2015PuppetLabs

Page 64: Fundamentals Puppet

git push

pushesupdatestoaremoterepository.Youroriginrepositoryislocatedonthemaster.Apost-updatehookwillupdatetheenvironmentworkingdirectory.

[root@training puppetcode]# git push origin master

Counting objects: 3, done.

Compressing objects: 100% (2/2), done.

Writing objects: 100% (3/3), 932 bytes, done.

Total 3 (delta 0), reused 0 (delta 0)

remote: Updating Puppet Environment training

remote: From /var/repositories/training

remote: * branch master -> FETCH_HEAD

To [email protected]:/var/repositories/training.git

* [new branch] master -> master ...

gitpush

Fundamentalsv3.4.9 64 ©2015PuppetLabs

Page 65: Fundamentals Puppet

Lab4.2:git push

Objective:

Pushyourlocalcodechangestotheclassroommasterrepository.

Lab4.2:gitpush

Fundamentalsv3.4.9 65 ©2015PuppetLabs

Page 66: Fundamentals Puppet

GitDevelopmentWorkflow

1. git pull origin master

2. Edit,validate,test

3. git add <code.pp>

4. git commit

5. git push origin master

6. Testondevelopmentinfrastructure

GitDevelopmentWorkflow

Fundamentalsv3.4.9 66 ©2015PuppetLabs

Page 67: Fundamentals Puppet

MoreaboutGit

Morecommandsandtopicsyoumaywanttoresearch:git diff

git log

git show

git blame <file>

git branch&git checkout

Resourcesyoumaybeinterestedin:FreeonlineGitbook

http://git-scm.com/book

LearnGitinyourbrowser

http://try.github.com/

MoreaboutGit

Fundamentalsv3.4.9 67 ©2015PuppetLabs

Page 68: Fundamentals Puppet

Lab4.3:ConfigurationofYourNode

Objective:

CreateandconfigureanodegroupforyourselfontheclassroomPuppetMaster.Pinyournodetothatnodegroupandclassifyitwithcustomization.

Lab4.3:ConfigurationofYourNode

Fundamentalsv3.4.9 68 ©2015PuppetLabs

Page 69: Fundamentals Puppet

Checkpoint:ClassroomEnvironment

HowdoescodemanagementrelatetothePuppetworkflow?

Usingversioncontrolmakesitdifficulttoundochanges.TrueFalse

Gitisonlyoneexampleofaversioncontrolsystem.TrueFalse

TheclassroommasterrunsaninstanceofGitHubEnterprise.TrueFalse

Someofthebenefitsofregularuseofversioncontrolrepositoriesinclude:MorestraightforwardcollaborationwithothersBuiltinunittestsforyourcodeIdentifyandvisualizechangesovertimeTestvariationsofyourcodebeforeputtingitintoproduction

Checkpoint:ClassroomEnvironment

Fundamentalsv3.4.9 69 ©2015PuppetLabs

Page 70: Fundamentals Puppet

BasicPuppetConcepts

BasicPuppetConcepts

Fundamentalsv3.4.9 70 ©2015PuppetLabs

Page 71: Fundamentals Puppet

Lesson5:BasicPuppetConcepts

Objectives

Attheendofthislesson,youwillbeableto:

IdentifythecorecomponentsofPuppet.Differentiatebetweendeclarativeandimperativeconfiguration.ExplainthebenefitsofusingPuppetforautomation.ReadthebasicsyntaxofPuppetdeclarations.

Lesson5:BasicPuppetConcepts

Fundamentalsv3.4.9 71 ©2015PuppetLabs

Page 72: Fundamentals Puppet

SolvingRealProblems

Imaginethatyouneedtomanageauser,Elmo.

Youcarespecificallyabout:

hisexistencehisprimarygrouphishomedirectory

SolvingRealProblems

Fundamentalsv3.4.9 72 ©2015PuppetLabs

Page 73: Fundamentals Puppet

ExistingUtilities

UsefuloperatingsystemleveltoolsUnix:

useradd/usermodgroupadd/groupmodmkdir

chmod

chown/chgrp

Windows:

net user

net localgroup

Notes:

Thesearejustsomeofthebuilt-incommandsthatwouldhelpyousolvethisproblem.Forthepurposeofthisthoughtexercise,we'relookingatbuilt-insystemtools,notdedicatedusermanagementsolutions.

OnaMicrosoftWindowssystem,youmightusetheLocalUsersandGroupssnap-intotheMicrosoftManagementConsole,PowerShellscriptingmethods,oryoumightusethenetcommandsabove,suchas:

net user /add puppet 'puppet8#labs'net localgroup administrators /add puppet

ExistingUtilities

Fundamentalsv3.4.9 73 ©2015PuppetLabs

Page 74: Fundamentals Puppet

CommandLineConcernsPlatformidiosyncrasies:

Doesthisboxhaveuseraddoradduser?Oh,superadduser.Super.

Whatwasthatflagagain?

Whatisthedifferencebetween-land-L?Whatdoes-rmean?

RecurseRemovereadprivilegesSystemuser

IfIrunthiscommandagain,whatwillitdo?

Notes:

Ifyou'retaskedwithmanagingmultipleplatforms,youmayhaveencounteredtoolsthatarenameddifferentlyandwhoseoptionflagsbehavedifferently.Manycommandsbehavecorrectlywhenyourunthemmultipletimes,butsomedon't.Theproceeduralnaturedoesnotgiveyouconsistentbehaviorwithouttheneedforextralogic.

CommandLineConcerns

Fundamentalsv3.4.9 74 ©2015PuppetLabs

Page 75: Fundamentals Puppet

DoItYourself

Youcoulddosomethinglikethis:

#! /bin/sh

USER=$1; GROUP=$2; HOME=$3

if [ 0 -ne $(getent passwd $USER > /dev/null)$? ]

then useradd $USER --home $HOME --gid $GROUP -n; fi

OLDGID=`getent passwd $USER | awk -F: '{print $4}'`

OLDGROUP=`getent group $OLDGID | awk -F: '{print $1}'`

OLDHOME=`getent passwd $USER | awk -F: '{print $6}'`

if [ "$GROUP" != "$OLDGID" ] && [ "$GROUP" != "$OLDGROUP" ]

then usermod --gid $GROUP $USER; fi

if [ "$HOME" != "$OLDHOME" ]

then usermod --home $HOME $USER; fi

Notes:

AnequivalentWindowsPowerShellscriptmightlooksomethinglike:

param (

[parameter(Position=0)]

[alias("user")][string]$userName,

[alias("group")][string]$groupName=$null,

[alias("home")][string]$homeDirectory=$null

)

# there are some much simpler ways to do this with the Active-Directory Module

# like Get-ADUser, Set-ADUser, etc but it is not installed on Win2008 (non-R2)

# and below so we want to prefer what works natively for all Windows machines

if ($userName -eq $null) { return "Error: Please pass in a User Name" }

$groups = @()

$currentHomeDirectory = $null

$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"

$adsiUser = $adsi.Children | ?{$_.SchemaClassName -eq 'user'} | `

?{$_.Name.ToString().ToLower() -eq "$userName".ToLower()}

if ($adsiUser -eq $null) {

$newUser = $adsi.Children.Add("$userName","user")

$newUser.CommitChanges()

$adsiUser = $newUser

} else {

$groups = $adsiUser.Groups() | %{$_.GetType().InvokeMember("Name", `

"GetProperty", $null, $_, $null)}

$currentHomeDirectory = $adsiUser.HomeDirectory.Value

DoItYourself

Fundamentalsv3.4.9 75 ©2015PuppetLabs

Page 76: Fundamentals Puppet

}

if ($groupName -ne $null) {

$adsiGroup = $adsi.Children | ?{$_.SchemaClassName -eq 'group'} | `

?{$_.Name.ToString().ToLower() -eq "$groupName".ToLower()}

if ($adsiGroup -eq $null) {

$newGroup = $adsi.Children.Add("$groupName","group")

$newGroup.CommitChanges()

$adsiGroup = $newGroup

}

if (! ($groups -contains "$groupName")) {

$adsiGroup.PSBase.Invoke("Add",$adsiUser.PSBase.Path)

}

}

# this may or may not be the correct thing to do because of HOMEDRIVE

if ($homeDirectory -ne $null) {

if ($currentHomeDirectory -ne $homeDirectory) {

pd$adsiUser.HomeDirectory = "$homeDirectory"

$adsiUser.CommitChanges()

}

}

DoItYourself

Fundamentalsv3.4.9 76 ©2015PuppetLabs

Page 77: Fundamentals Puppet

Butwhatabout...Robusterrorchecking?Supportingotherplatforms?Robustloggingofchanges?Readablecode?

Andmanagingusersiseasy.

Howwouldyoukeepcronjobs,packages,andservicesinaconsistentstateacrossyourinfrastructure?

Butwhatabout...

Fundamentalsv3.4.9 77 ©2015PuppetLabs

Page 78: Fundamentals Puppet

ThePuppetWay

Alightattheendofthetunnel:

user { 'elmo':

ensure => present,

gid => 'sysadmin',

home => '/mnt/home/elmo',

managehome => true,

}

Notes:

ThisisastandardPuppetresourcethatsimplydescribesthestatethatwewouldlikethisusertoexistin.Puppetwillbringtheresourceintocompliancebyperforminganyrequiredactionstomaketheusermatchthisdesiredstate.

Tobeperfectlyaccurate,thisisn'tcompletelyplatformindependent,becauseWindowsdoesn'thavetheconceptofaprimarygroupanddoesn'tallowcreationofuserswithoutpasswords.We'lltalkaboutwaystohandlethatlaterinthecourse.

ThePuppetWay

Fundamentalsv3.4.9 78 ©2015PuppetLabs

Page 79: Fundamentals Puppet

DesiredState

Describethestateyouwant.

DesiredState

Fundamentalsv3.4.9 79 ©2015PuppetLabs

Page 80: Fundamentals Puppet

RobustLogging

Anyconvergenceactionsarereported.

RobustLogging

Fundamentalsv3.4.9 80 ©2015PuppetLabs

Page 81: Fundamentals Puppet

MaintainingStateYouprovisionanode.Puppetconfiguresit.Puppetmaintainsthedesiredstate.

MaintainingState

Fundamentalsv3.4.9 81 ©2015PuppetLabs

Page 82: Fundamentals Puppet

InfrastructureasCode

orExecutableDocumentationclass sysadmins {

user { 'elmo':

ensure => present,

groups => ['sysadmin','web','dbadmin'],

managehome => true,

}

group { 'sysadmin':

ensure => present,

}

}

DescriptiveStraightforwardTransparentPortableacrossplatforms

InfrastructureasCode

Fundamentalsv3.4.9 82 ©2015PuppetLabs

Page 83: Fundamentals Puppet

Idempotency

Puppetonlymakesconfigurationchangesifrequired.

# First Puppet Run

notice: /Group[sysadmin]/ensure: created

notice: /User[elmo]/ensure: created

notice: Finished catalog run in 0.08 seconds

# Second Puppet Run

notice: Finished catalog run in 0.03 seconds

Idempotence:Thepropertyofcertainoperationsinmathematicsorcomputerscienceinthattheycanbeappliedmultipletimeswithoutfurtherchangingtheresultbeyondtheinitialapplication.

Notes:

Idempotent-abletobeappliedmultipletimeswiththesameoutcome.Puppetresourcesareidempotent,sincetheydescribeadesiredfinalstateratherthanaseriesofstepstofollow.Puppetonlymakeschangesifchangesarerequiredtobringthenodeintocompliance.http://docs.puppetlabs.com/references/glossary.html#idempotent

Idempotency

Fundamentalsv3.4.9 83 ©2015PuppetLabs

Page 84: Fundamentals Puppet

PuppetResourcesResourcesarebuildingblocks.Theycanbecombinedtomakelargercomponents.Togethertheycanmodeltheexpectedstateofyoursystem.

PuppetResources

Fundamentalsv3.4.9 84 ©2015PuppetLabs

Page 85: Fundamentals Puppet

ResourceDeclarations

Resourcesaremanagedintermsofattributes.InstructPuppettomanageapackage:

package { 'openssh':

ensure => present,

}

InstructPuppettomanageauser:

user { 'elvis':

ensure => absent,

}

AttributesdescribethestatethatPuppetshouldconvergetheresourceto.Youmanagejustwhatyouwanttomanage.

Notes:

Bymanagingresourcesandtheattributesofthoseresources,weletPuppetknowwhatthingsthatwecareabout.Attributesnotdescribedexplicitlyarenotmanaged,sotheywilleitherbeunsetorwillbesettooperatingsystemdefaults.Forexample,intheopensshpackageexample,wehavenotspecifiedtheversion,sothelatestpackageavailableinyourconfiguredrepositorieswouldbeinstalled.

manageToconfigurethestateofaresource,suchasafile,apackage,orauserasalistofattributesorpropertiesofthatresourceandthevaluethateachattributeshouldbesetto.Forexample,anattributeofyourcarmightbethatthecolorisblue.

ResourceDeclarations

Fundamentalsv3.4.9 85 ©2015PuppetLabs

Page 86: Fundamentals Puppet

UserResource

SampleAttributesuid:Theuser'suidnumber.groups:Listofgroupsthatthisuserbelongsto.home:Theuser'shomedirectory.shell:Theuser'sloginshell.

Wanttoknowmore?

$ puppet describe user

- **comment**

A description of the user. Generally the user's full name.

- **ensure**

The basic state that the object should be in. Valid values are

`present`, `absent`, `role`.

......

......

Notes:

puppet describetakesaresourcetypeasanargument.Itreturnsdetaileddocumentationonthatspecificresourcetypeandisgeneratedfromthesamesourcethatweuseforhttp://docs.puppetlabs.com/references/latest/type.html.

UserResource

Fundamentalsv3.4.9 86 ©2015PuppetLabs

Page 87: Fundamentals Puppet

ResourceDeclarations# Type is 'user'

# Title is 'elmo'

user { 'elmo':

ensure => present, # Ensure the user exists

groups => [ 'sysadmins' 'puppetusers' ], # Groups the user should belong to

password => $super_secret_password, # Use the value of the variable

}

Typeandtitlepairsmustbeuniqueforanode.

Notes:

Declarationsstartwiththeresourcetypeinlowercase.Curlybracesdefinetheresourceblock.Separatethetitlefrombodywithacolon.Bodyconsistsofalistofattributesandvalues.Usealphanumerics&quotestrings.Bestpracticesuggestions:

Youshouldalwaysquotestrings,evenwhennotstrictlyrequired.Youshouldincludeacommaafterthelastattributeinablockbecauseitreducesmaintenanceerrors.

Justliketherecanonlybeonefileatagivenpath,therecanonlyeverbeoneresourceofagiventypeandname.Forexample,therecannotbetwouserresourcesnamedelmo.ThisissoPuppetandtheoperatingsystemcanidentifyeachresourceindividually.

Noticethatwesettheuserpasswordtothevalueofavariable.We'lltalklaterabouthowyoucankeepspecificconfigurationdataseparatefromyourcode.

ResourceDeclarations

Fundamentalsv3.4.9 87 ©2015PuppetLabs

Page 88: Fundamentals Puppet

DeclarativeModelingLanguageModelthedesiredstate.LetPuppetfigureouthowtoenforceit.

ComparisonImperative Declarative

if [ 0 -ne $(getent passwd elmo > /dev/null)$? ]then useradd elmo --gid sysadmin -nfi

GID=`getent passwd elmo | awk -F: '{print $4}'`GROUP=`getent group $GID | awk -F: '{print $1}'`

if [ "$GROUP" != "$GID" ] && [ "$GROUP" != "sysadmin" ]then usermod --gid $GROUP $USERfi

user { 'elmo': ensure => present, gid => 'sysadmin',}

if [ "`getent group sysadmin | awk -F: '{print $1}'`" == "" ]then groupadd sysadminfi

group { 'sysadmin': ensure => present,}

Notes:

Ifyouwanttodescribeyourendstateinashellscript,youendupwithsomethingdifficulttoreadandprovideasdocumentationtopeers.WithaPuppetresourcedeclaration,theend-stateisclearlydefinedandeasytoread,evenforthoseunfamiliarwithPuppet.

ImperativeAlistofstepsorinstructionsusedtoaccomplishatask.Oftenexcruciatinglydetailed.

DeclarativeRatherthanprovidingeachinstruction,simplydescribetheexpectedendresult.

DeclarativeModelingLanguage

Fundamentalsv3.4.9 88 ©2015PuppetLabs

Page 89: Fundamentals Puppet

Abstraction

ResourcesinPuppetareabstractedfromunderlyingproviders.

package { 'postgresql':

ensure => present,

}

Thisresourcedeclarationwillusedifferenttoolsondifferentplatforms:

Redhatfamily

yum install postgresql

Debianfamily

apt-get install postgresql

Windows(withChocolateyinstalled)

choco install postgresql

Notes:

SpecificationinthePuppetDSLtranslatestoimplementationviatheproviderchosenfortheplatformtheagentisrunningon.

AbstractionRemovesresponsibilityforimplementationdetailsfromtheenduser.Inthisexample,youdon'tneedtoknowwhattoolsareusedtoinstallPostgreSQL.YoujusttellPuppetthatyouwantthepackagetobepresentonthesystemandyoucantrustthatPuppetwillensurethatstate.

Abstraction

Fundamentalsv3.4.9 89 ©2015PuppetLabs

Page 90: Fundamentals Puppet

ResourceAbstractionLayerProvidesaconsistentmodelforresourcesacrosssupportedplatforms.

ResourceAbstractionLayer

Fundamentalsv3.4.9 90 ©2015PuppetLabs

Page 91: Fundamentals Puppet

TypesSimilarresourcesaregroupedintoresourcetypes.

Theinterfacelayerdescribesresourceattributeswecanconfigure.

Types

Fundamentalsv3.4.9 91 ©2015PuppetLabs

Page 92: Fundamentals Puppet

ProvidersEachresourcetypehasoneormoreproviders.

Theimplementationlayertranslatesintooperatingsystemactions.

Providers

Fundamentalsv3.4.9 92 ©2015PuppetLabs

Page 93: Fundamentals Puppet

ManyProviders

Providersforthepackagetype:

[root@training ~]# ls /opt/puppet/lib/ruby/[...]/puppet/provider/package

aix.rb fink.rb opkg.rb ports.rb windows

appdmg.rb freebsd.rb pacman.rb portupgrade.rb windows.rb

apple.rb gem.rb pip.rb rpm.rb yumhelper.py

aptitude.rb hpux.rb pkgdmg.rb rug.rb yumhelper.pyc

apt.rb macports.rb pkgin.rb sunfreeware.rb yumhelper.pyo

aptrpm.rb msi.rb pkg.rb sun.rb yum.rb

blastwave.rb nim.rb pkgutil.rb up2date.rb zypper.rb

dpkg.rb openbsd.rb portage.rb urpmi.rb

Supportformostpackagemanagers.Operatingsystemnativeandthird-party.

Notes:

Somepackagetypescanretrievetheirownpackagefiles,whileotherscannot.Forthosepackageformatsthatcannotretrievetheirownpackagefiles,youcanusethesourceparametertopointtothecorrectfileorURI.

# Using the Windows provider

package { 'mysql':

ensure => present,

source => '//corpserver/installers/mysql-5.5.16-winx64.msi',

provider => windows,

}

# Using the RPM provider

package { 'mysql':

ensure => present,

source => 'http://internal.mycorp.net/packages/redhat/6/mysql-5.5.16-x86_64.rpm',

provider => rpm,

}

http://docs.puppetlabs.com/references/latest/type.html#package

ManyProviders

Fundamentalsv3.4.9 93 ©2015PuppetLabs

Page 94: Fundamentals Puppet

PackageManagers

Simplifytheinstallationofsoftware

C:\Users\Administrator> choco install nginx

Chocolatey (v0.9.8.23) is installing 'nginx' and dependencies. By installing you

accept the license for 'nginx' and each dependency you are installing.

[...]

Reading environment variables from registry. Please wait... Done.

C:\Users\Administrator>

Packagemanagerssimplifytheinstallationofsoftware.Mostpackagemanagersautomatically:

retrievepackagefilesfromtheInternet.installorupgradepackagedependencies.

Third-partypackagemanagerscanextendoperatingsystemnativetools.Wehavepre-installedtheChocolateypackagemanageronWindowsclientsintheclassroomandsetitasthedefaultpackageprovider.

Notes:

APuppetresourceformanagingthispackagemightlooklikethefollowing:

package { 'nginx':

ensure => present,

provider => chocolatey,

}

PackageManagers

Fundamentalsv3.4.9 94 ©2015PuppetLabs

Page 95: Fundamentals Puppet

Checkpoint:BasicPuppetConcepts

Whatdoesitmeantomanageconfigurationstate?

RunningthePuppetAgentmultipletimesisasafeoperation.TrueFalse

Configurationdriftonlyoccurswhenunauthorizedmanualchangestakeplace.TrueFalse

Combiningresourcesintolargercomponentsoftenleadstodependencyerrors.TrueFalse

WhataresomeofwaysthatthePuppetlanguageisreadable?UtilitymethodsareprovidedtocheckcommandexitcodesAllresourcetypesareinteractedwithinverysimilarwaysMostresourcetypescanbeusedondifferentplatformswithoutmodificationRobustconcurrencyprimitivesareprovideddirectlyinthelanguageItcomeswithaglossaryyoucangivetoyourboss

Checkpoint:BasicPuppetConcepts

Fundamentalsv3.4.9 95 ©2015PuppetLabs

Page 96: Fundamentals Puppet

ModulesandClasses

ModulesandClasses

Fundamentalsv3.4.9 96 ©2015PuppetLabs

Page 97: Fundamentals Puppet

Lesson6:ModulesandClasses

Objectives

Attheendofthislesson,youwillbeableto:

Describethestructureof,build,anduseabasicPuppetmodule.Describethebenefitsofusingamoduletocontainconfiguration.ExplainhowmodulesallowPuppettoauto-loadcontent.Differentiatebetweendefininganddeclaringclasses.

Lesson6:ModulesandClasses

Fundamentalsv3.4.9 97 ©2015PuppetLabs

Page 98: Fundamentals Puppet

PuppetClassesClassesdefineacollectionofresourcesthataremanagedtogetherasasingleunit.

# /etc/puppetlabs/puppet/environments/production/modules/ssh/manifests/init.pp

class ssh {

package { 'openssh':

ensure => present,

}

file { '/etc/ssh/sshd_config':

ensure => file,

owner => 'root',

group => 'root',

mode => '0644',

require => Package['openssh'],

source => 'puppet:///modules/ssh/sshd_config',

}

service { 'sshd':

ensure => running,

enable => true,

require => File['/etc/ssh/sshd_config'],

}

}

Notes:

Statedanotherway,package,file,andserviceareindividualPuppetresourcesbundledtogethertodefineasingleidea,orclass.Classdefinitionsarecontainedinmanifests.Theinit.ppfileaboveisanexampleofamanifestwritteninPuppetDSL.Notethatthereisatrailingcommaafterthelastattributeineachresourceabove.Thisisnotrequired,butisbestpracticesbecauseitreducesthechancesoferrorsthroughoutthelifetimeofthemanifestfile.

Agooddesignstrategyistomakemanysmallerclassesthatrepresentlogicalconfigurationgroupingsandcanbestackedtogetherindifferentways.Thistakesalittlemoredesignworkupfront,butbecomesmuchmoremaintainablethanlargemonolithicclassesveryquickly.

Learninghowtostructureyourclassestomakethemcomposableinthiswayisanartthatwillbeimprovewithpractice.

PuppetClasses

Fundamentalsv3.4.9 98 ©2015PuppetLabs

Page 99: Fundamentals Puppet

ModulesModulesaredirectoriesthatcontainyourconfiguration.Theyaredesignedtoencapsulateallofthecomponentsrelatedtoagivenconfigurationinasinglefolderhierarchy.

Theyhaveapre-definedstructurethatenablesthefollowing:

auto-loadingofclassesfile-servingfortemplatesandfilesauto-deliveryofcustomPuppetextensionseasysharingwithothers

Notes:

Modulesshouldbeself-containedandshouldhavewelldefinedintegrationpointsforothermodulestouse.Eachmoduleshouldmanageeverythingtodowiththethingthatitismanaging,and--moreimportantly--shouldnotmanagethingsthatdon'tfallwithinit'sscope.Forexample,awebappshouldnotmanagetheMySQLorApacheconfigurationbecausethenyoucouldeveronlyuseoneatatime.

Learninghowtoappropriatelydefinelayersofabstractionisaskillthatcomeswithpractice.

Modules

Fundamentalsv3.4.9 99 ©2015PuppetLabs

Page 100: Fundamentals Puppet

Auto-loadingofClasses

Modulesenableclassauto-discovery.First,Puppetneedstoknowwheretofindyourmodules.

# puppet.conf on puppet master

[main]

basemodulepath = /etc/puppetlabs/puppet/modules:/opt/puppet/share/puppet/modules

environmentpath = /etc/puppetlabs/puppet/environments

...

Then,yourclassesareplacedinthispredictablestructure.

[root@training ~]# tree /etc/puppetlabs/puppet/environments/production/modules/ssh/

...

├── manifests ├── init.pp ## class ssh { ... } └── server.pp ## class ssh::server { ... }

Puppetexpectstofindclassesinthemanifestsdirectoryofyourmodule.

Notes:

Becausemodulesarecompletelyself-contained,theyarerelocatable.Thismeansthattheycanbeplacedanywhereinyourmodulepathandcanbemovedorsharedeasily.Noticethatmultipleentriesinthemodulepathareallowed.Puppetwillsimplysearchthroughthemuntilitfindsthemodule&classitislookingfor.

Themodulepathisconstructedofyourenvironment'smodulepathplusthebasemodulepath,

Deprecationwarning:

Whenreadingotherusers'code,youmayrunacrossthepracticeofimportingmanifestfiles.ThisisathrowbacktoancientcodefrombeforePuppethadtheconceptofself-containedmodules.Thisisbadpracticetodaybecauseitleadstoinflexiblecodethatissusceptibletobreakageandgenerallynotreusableatall.

Someuserswithsmallinfrastructuresprefertouseimporttostorenodedefinitionsinindividualfiles.However,notethatthisrequiresyoutorestartthepuppetmasterortouchsite.ppwheneveryouedityournodedefinitionsandleadstobrittleandrigidarchitectures.Thispracticehasbeenobsoletedbymodernnodeclassificationschemes.

Bestpracticesaretocompletelyavoidtheimportkeyword.

Auto-loadingofClasses

Fundamentalsv3.4.9 100 ©2015PuppetLabs

Page 101: Fundamentals Puppet

Auto-loadingofClasses

Classnamescanbebrokenintonamespaces.

ClassnamesmapdirectlytowherePuppetexpectstofindthem.

Thefirstsegmentinanameidentifiesthemodule.Thefinalsegmentinanameidentifiesthefilename.Anyintermediarysegmentsareevaluatedassubdirectoriesofthemodule'smanifestsdirectory.Themodule'sdefaultclassislocatedinthemanifests/init.ppfileandhasthesamenameasthemoduleitself.

[root@training ~]# tree /etc/puppetlabs/puppet/environments/production/modules/apache/

...

├── manifests ├── init.pp ## class apache { ... } ├── mod │ └── php.pp ## class apache::mod::php { ... } └── mod.pp ## class apache::mod { ... }

Wherewouldweexpecttofindtheclassfoo::bar::baz?

Auto-loadingofClasses

Fundamentalsv3.4.9 101 ©2015PuppetLabs

Page 102: Fundamentals Puppet

Lab6.1:BuildYourFirstModule

Objective:

ConstructyourfirstPuppetModuletomanageasimpleresource.Testyourmodulebyvalidatingsyntaxonly.

Lab6.1:BuildYourFirstModule

Fundamentalsv3.4.9 102 ©2015PuppetLabs

Page 103: Fundamentals Puppet

DefineandDeclareNowthatwehavebuiltourclass,howdoweuseit?

define:Tospecifythecontentsandbehaviorofaclass.Definingaclassdoesn'tautomaticallyincludeitinaconfiguration;itsimplymakesitavailabletobedeclared.

declare:TodirectPuppettoincludeorinstantiateagivenclass.Todeclareclasses,usetheincludefunction.ThistellsPuppettoevaluatetheclassandmanagealltheresourcesdeclaredwithinit.

Notes:

DefiningaclassissimilartodefiningafunctioninalanguagelikeRuby,Python,orC.Thefunctiononlyeverhaseffectwhenitisinvoked.Similarly,Puppetclassdefinitionsdon'thaveanyeffectuntilwedeclarethem.

Besidestheincludefunction,theresource-likeclass {'foo':}syntaxcanbeused.Thisishowwedeclareparameterizedclassesandwillbecoveredinalatersection.

DefineandDeclare

Fundamentalsv3.4.9 103 ©2015PuppetLabs

Page 104: Fundamentals Puppet

DefiningvsDeclaringWhenyoubuildaclasslikethefollowing,youaredefiningit.

class ssh {

package { 'openssh':

ensure => present,

}

file { '/etc/ssh/sshd_config':

ensure => file,

owner => 'root',

group => 'root',

require => Package['openssh'],

source => 'puppet:///modules/ssh/sshd_config',

}

service { 'sshd':

ensure => running,

enable => true,

require => File['/etc/ssh/sshd_config'],

}

}

Touseit,youneedtodeclaretheclass.

include ssh

DeclaringaclassinstructsPuppettoenforcetheclass.

Notes:

Aclassdefinitionisonlyevaluatedandenforcedonceitisincluded.

DefiningvsDeclaring

Fundamentalsv3.4.9 104 ©2015PuppetLabs

Page 105: Fundamentals Puppet

ClassesareSingletonClassesareuniqueandwillonlybeusedonceonagivennode.

class ssh {

package { 'openssh':

ensure => present,

}

file { '/etc/ssh/sshd_config':

ensure => file,

owner => 'root',

group => 'root',

require => Package['openssh'],

source => 'puppet:///modules/ssh/sshd_config',

}

service { 'sshd':

ensure => running,

enable => true,

require => File['/etc/ssh/sshd_config'],

}

}

include ssh

include ssh

Thecompiledcatalogwillonlyevercontainasingleinstanceofaclass.

Notes:

Classes,justlikeresources,canonlybedeclaredonce.Therecanonlybeoneinstanceofaclassinthecatalog.Theincludefunctionwilldeclareaclassifandonlyifithasn'tbeendeclaredalready.Itworkssimilarlytotherequire_oncefunctioninotherlanguages.

Thismeansthatbestpracticesaretoincludeaclasswhenit'sgoingtobereferenced;eventhoughtheincludefunctionmaybecalledmanytimes,theclassisonlyeveractuallydeclaredonce.

ClassesareSingleton

Fundamentalsv3.4.9 105 ©2015PuppetLabs

Page 106: Fundamentals Puppet

DeclarationTesting

Preparingtotestourdeclarations:Saveexampleusage(classdeclarations)withthemodule.

adhoctestingduringdevelopmentexampleusagewhensharingwithothers

[root@training ~]# tree /etc/puppetlabs/puppet/environments/production/modules/ssh

├── manifests│ ├── init.pp ## class ssh { ... }│ └── server.pp ## class ssh::server { ... }└── examples ├── init.pp ## include ssh └── server.pp ## include ssh::server

Eachsmoketestshoulddeclaretheclassitistesting.

# /etc/puppetlabs/puppet/environments/production/modules/ssh/examples/init.pp

include ssh

DeclarationTesting

Fundamentalsv3.4.9 106 ©2015PuppetLabs

Page 107: Fundamentals Puppet

Thepuppet applyExecutableCompilespuppetmanifestintoaresourcecatalog.UsestheResourceAbstractionLayertosimulateorenforcethecataloglocally.

Notes:

Inagent/masterPuppetarrangements,agentnodessendtheirfactstothemaster,andthemastercompilesthecatalogusingthesefacts.Whenusingpuppet apply,localfactsareusedtobuildthecatalog.Whenusingpuppet apply,remembertoapplyagainstfilesinthetestsdirectory,notinthemanifestsdirectory.Filesinthemanifestsdirectorycontaintheresourcedefinitions,buttoimplement,definedresourcesneedtobedeclaredandthefilesinthetestsdirectorycontainthedeclaration,whichwillactuallyinitiateaction.Thereisnoharminrunningpuppet applyagainstfilesinthemanifestsdirectory,butthiswillnotapplyanychanges.Runningpuppet applyagainstfilesinthetestsdirectorycanbeusedasanadhocverificationorproofofconcepttoseehowthemodulewillmanagethesystemonceimplemented.

ThepuppetapplyExecutable

Fundamentalsv3.4.9 107 ©2015PuppetLabs

Page 108: Fundamentals Puppet

ApplyingaSmokeTest

One-offmanifestenforcement.Validateyourcode.Enforceaclasslocallyonetimeonly.TemporarychangesthatmaybeoverriddenonthenextAgentrun.puppet applycompilesamanifestfileandenforcesitimmediately.

[root@training ssh]# puppet apply examples/init.pp

notice: /Stage[main]/Ssh/Service[sshd]/ensure: ensure changed 'stopped' to 'run...

notice: Finished catalog run in 0.14 seconds

ApplyingaSmokeTest

Fundamentalsv3.4.9 108 ©2015PuppetLabs

Page 109: Fundamentals Puppet

SimulatingChangewithPuppet

--noopmodesimulateswithoutenforcing.ResourceAbstractionLayercansimulateeventsratherthantakingaction.Informyouofsystemdriftandexpectedconvergenceactions.

[root@training sudoers]# puppet apply --noop examples/init.pp

notice: //File[/etc/sudoers]/mode: current_value 0646, should be 0440 (noop)

notice: Finished catalog run in 0.03 seconds

Individualresourcesmayalsobeplacedinnoopmode.

package { 'kernel':

ensure => latest,

noop => true,

}

Notes:

BecausePuppetcaninspectthecurrentstateofyoursystemandknowshowtodeclareyourresourcetobepresentorabsentstatefully,itcaninspectwhatthecurrentstateofyoursystemisandgiveyoumeaningfulinformationaboutwhatitwouldtaketoconfigureyoursystemfromitsrunningstatetothestateyouhavedeclaredinyourPuppetmanifests.

The--noopflagcanbeusedinboththeapplyandagentroles.Itcanalsobeappliedtoindividualresourcesinthemanifestitself.Forexample,justlike--noopastheparameterforpuppet apply,youcanenablesimulationforindividualresourceswhenyouwanttomonitorwhatwouldhappenforagivenresource,shoulditbeenforced.

HavingsimulationcapabilitiesbuiltintoeveryPuppettypewithoutadditionaleffortfromthesystemsadministratorispartofwhatseparatesPuppetfromotherconfigurationmanagementtools.

SimulatingChangewithPuppet

Fundamentalsv3.4.9 109 ©2015PuppetLabs

Page 110: Fundamentals Puppet

SimulatingChangewithPuppet

--noopmodesimulateswithoutenforcing.

Onceconvergenceactionsareverified,Puppetcanberunwithout--nooptoenforcethechangeinstate.

[root@training sudoers]# puppet apply --noop examples/init.pp

notice: //File[/etc/sudoers]/mode: current_value 0646, should be 0440 (noop)

notice: Finished catalog run in 0.03 seconds

[root@training sudoers]# puppet apply examples/init.pp

notice: //File[/etc/sudoers]/mode: mode changed '0646' to '0440'

notice: Finished catalog run in 0.03 seconds

SimulatingChangewithPuppet

Fundamentalsv3.4.9 110 ©2015PuppetLabs

Page 111: Fundamentals Puppet

Lab6.2:UseYourModule

Objective:

CreateasmoketestforsanitycheckingEnforceyourusersclassonyourlocalagent.

Lab6.2:UseYourModule

Fundamentalsv3.4.9 111 ©2015PuppetLabs

Page 112: Fundamentals Puppet

AGroupResourceDeclarationgroup { 'sysadmin':

ensure => present,

gid => '5000',

}

AdditionalAttributesname:Thegroupname.ensure:Groupresourcestate.Validvaluesarepresent,absent.gid:ThenumericalgroupID.members:Membersofthegroup.

AGroupResourceDeclaration

Fundamentalsv3.4.9 112 ©2015PuppetLabs

Page 113: Fundamentals Puppet

PuppetDescribeWanttoknowmore?

[root@training sudoers]# puppet describe group

- **allowdupe**

Whether to allow duplicate GIDs. This option does not work on

FreeBSD (contract to the `pw` man page). Valid values are `true`,

`false`.

- **attribute_membership**

Whether specified attribute value pairs should be treated as the only

attributes of the user or whether they should merely be treated as the

minimum list. Valid values are `inclusive`, `minimum`.

......

......

PuppetDescribe

Fundamentalsv3.4.9 113 ©2015PuppetLabs

Page 114: Fundamentals Puppet

Lab6.3:ExpandYourModule

Objective:

Extendyourmoduletomanagemultipleresourcetypes.Test&applytheclasslocally.

Lab6.3:ExpandYourModule

Fundamentalsv3.4.9 114 ©2015PuppetLabs

Page 115: Fundamentals Puppet

Checkpoint:ModulesandClasses

HowisPuppetcodeorganizedandused?

FollowingthemoduledirectorystructureallowsPuppettofindandloadclasseswhentheyaredeclared.

TrueFalse

Documentationonaresourcetypecanbefoundbyrunningthecommand:puppetresource{resource-type}--helppuppetdescribe{resource-type}puppet{resource-type}--help

YouinstructPuppettoenforcetheconfigurationinaclassby:requiringitincludingitRunningpuppetapplyontheclassfile

WhataresomeBestPracticesfororganizingPuppetcode?CombiningrelatedclassesintoasinglefileisrecommendedforreadabilityFormaximumcompatibility,thevimtexteditorshouldbeusedtowritePuppetcodeClassesshouldcontainonlydirectlyrelatedresourcesFunctionalityshouldbeorganizedintodiscreteclassesofrelatedresources

Checkpoint:ModulesandClasses

Fundamentalsv3.4.9 115 ©2015PuppetLabs

Page 116: Fundamentals Puppet

Classification

Classification

Fundamentalsv3.4.9 116 ©2015PuppetLabs

Page 117: Fundamentals Puppet

Lesson7:Classification

Objectives

Attheendofthislesson,youwillbeableto:

Explaintheconceptofnodeclassification.Writeanodedeclarationinyoursitemanifest.UseclassificationrulesinthePuppetEnterpriseConsole.Assignnodestonodegroups.

Lesson7:Classification

Fundamentalsv3.4.9 117 ©2015PuppetLabs

Page 118: Fundamentals Puppet

Mainmanifestsetting

Thestartingpointforcatalogcompilation.ThestandardmanifestfileforthePuppetMaster.Compiledanytimeanagentconnectsandrequestsacatalog.Cancontainglobalresourcesandclassesthatapplytoallnodesequally.PuppetEnterpriseusesittoconfigurefilebackups.Environmentmanifestsin$environmentpath/$environment/manifestsManifestfilesevaluatedindirectoryglobbingorder.

Notes:

Settingaglobalvalueformanifestinpuppet.confisdeprecated.Pleaseusedirectoryenvironmentsinstead.Formoreinfo,seehttp://docs.puppetlabs.com/puppet/latest/reference/environments.html

OnWindows,thePuppetEnterprisedefaultlocationofsite.ppisC:\ProgramData\PuppetLabs\puppet\etc\manifests\site.pp.AsonlytheAgentrunsonWindows,thismanifestisonlyusefulfortestingpurposes.

Mainmanifestsetting

Fundamentalsv3.4.9 118 ©2015PuppetLabs

Page 119: Fundamentals Puppet

NodeDefinitions

Includenodespecificconfiguration.Puppetnodedefinitionslooksimilartoclasses.ThenodedefinitioncorrespondingtotheAgent'snameisdeclaredautomatically.Onlyonenodedefinitioniseverdeclared.Bydefault,theAgentnode’snameisitscertname.

node 'foo.puppetlabs.com' {

include ssh

}

Whenthenodefoo.puppetlabs.comconnectstothePuppetMaster,itwillbeassignedthesshclass.

Notes:

Anagentnode'scertnameishowitisidentifiedinthePuppetnetwork.Itissetatinstalltimebutcanbechangedlater.Thecertnameisusually(butnotalways)thenode'sfullyqualifieddomainname.

Bestpracticesaretoavoidanycomplexlogicinnodedefinitionsandsimplyincludetherequiredclasses.Thisleadstoaconfigurationmodelthatismorereadableandmorecomposable.ItalsomakesthetransitiontoanExternalNodeClassifierliketheEnterpriseConsoleapainlessprocess.

NodeDefinitions

Fundamentalsv3.4.9 119 ©2015PuppetLabs

Page 120: Fundamentals Puppet

NodeDefinitions

Multipleclassesaredeclaredtogethertorepresentarole.

Forexample,tobuildawebapplicationfromPuppetclassesonoscar.example.com:

node 'oscar.example.com' {

include ssh

include apache

include mysql

include web_app

}

Notes:

ThisisanodedefinitionwhichrepresentstheagentmachineandtheclassesthatcomposeitsPuppetconfiguration.Whenthenodeoscar.example.comrequestsacatalogfromthemaster,theseclasseswillbeusedtobuildit.

Nodedefinitionscanmatchbasedonsimplestrings,likeabove,ortheycanmatchbasedonregularexpressions.Regularexpressionsareonlyusedwhennoexactmatchisfound,andtheyarecomparedinorderuntilaregexmatches,regardlessofspecificity.

Bestpracticesaretoavoidanycomplexlogicinnodedefinitionsandsimplyincludetherequiredclasses.Thisleadstoaconfigurationmodelthatismorereadableandmorecomposable.ItalsomakesthetransitiontoanExternalNodeClassifierliketheEnterpriseConsoleapainlessprocess.

NodeDefinitions

Fundamentalsv3.4.9 120 ©2015PuppetLabs

Page 121: Fundamentals Puppet

RegularExpressions

Configurenodesbynodenamepatterns.Regularexpressionsareonlyevaluatedifnoexactmatchisfound.Regularexpressionscanbeusedtodefinenodes.Thefirstmatchfoundisdeclared,regardlessofspecificity.

node /^web\d{3}\.puppetlabs\.com$/ {

include ssh

include apache

include mysql

include web_app

}

Whenawebapplicationserver,identifiedbyanodenameofwebXXX,connectstothePuppetMaster,itwillbeassignedtheclassesabove.

Notes:

Rememberthatregularexpressionsarenotasreadableassimplestringsare.Assuch,bestpracticesareto,whenpossible,minimizetheuseofregularexpressionstomakeitmoreclearwhichnodedefinitionwillbeenforced.Seehttp://docs.puppetlabs.com/puppet/3/reference/lang_node_definitions.htmlformoreinformation.

RegularExpressions

Fundamentalsv3.4.9 121 ©2015PuppetLabs

Page 122: Fundamentals Puppet

DefaultNode

Whennoothernodedeclarationmatches.

node default {

notify { "${::fqdn} has no node definition": }

}

Youcanspecifyanodenameddefault.Thiswillbeusedifnodirectlymatchingnodeisfound.Sometimesusedwhenmanyofonlyasingletypeofsystemareonanetwork.

DefaultNode

Fundamentalsv3.4.9 122 ©2015PuppetLabs

Page 123: Fundamentals Puppet

ClassesareReusableComposablenodeconfigurations.Saveseffortandreduceserror.

Notes:

Designingreusableclassesmeansthatnodeconfigurationscanbecomposedbystackingclassestogether,whichisbothmorereliableandmoreefficientthanwritingeachconfigurationfromthegroundup.

Defineyourinfrastructurebysimplyassigningclassestonodesasneeded.

ClassesareReusable

Fundamentalsv3.4.9 123 ©2015PuppetLabs

Page 124: Fundamentals Puppet

Demo

$environmentpath/production/manifests/site.pp

Demo

Fundamentalsv3.4.9 124 ©2015PuppetLabs

Page 125: Fundamentals Puppet

Definerulestoaddnodestoagroup

Notes:

Notethatthedomainruledoesn'tmatchanynodesyet,evenwithavalidcomparison,becausewehaven'tyetselectedafacttocomparewith.

Definerulestoaddnodestoagroup

Fundamentalsv3.4.9 125 ©2015PuppetLabs

Page 126: Fundamentals Puppet

Pinnodestoagroup

Notes:

Pinningisashortcutforcreatingarulethatmatchesexactlyonenodename.

Pinnodestoagroup

Fundamentalsv3.4.9 126 ©2015PuppetLabs

Page 127: Fundamentals Puppet

Classifyanodegroup

Classifyanodegroup

Fundamentalsv3.4.9 127 ©2015PuppetLabs

Page 128: Fundamentals Puppet

Nodedefinition

Summarizestheeffectofallmatchingclassificationrules

Hasasimilareffectas:

node 'clark.puppetlabs.vm' {

include userprefs

include classroom::course::fundamentals

include puppet_enterprise

include puppet_enterprise::profile::mcollective::agent

}

Notes:

Thisimagecomesfromthenodeoverviewpageforasinglenode,notfromthenodegroupinterface.Nodesarenolongerediteddirectly;theclassificationtheyreceiveisanaggregateoftheclassificationappliedtoeachnodegroupthatitisamemberof.

Notethatthere'snodirectequivalenttoConsolenodegroupsinsite.pp.

Nodedefinition

Fundamentalsv3.4.9 128 ©2015PuppetLabs

Page 129: Fundamentals Puppet

Demo

ClassificationofnodeswiththeConsole.

Demo

Fundamentalsv3.4.9 129 ©2015PuppetLabs

Page 130: Fundamentals Puppet

AddingaclasstotheConsole.

PriortoPE3.7classeshadtobeaddedmanually

NodescanonlybeclassifiedwithclassesthattheConsoleisawareof.OlderversionsoftheConsolerequiredtheusertoaddclassestoitsdatabase.ClasseswerelistedintheConsolesidebar.ClicktheAddclassesbuttontoaddanewclasstothelist.PE3.7andaboveauto-discoverclasses.Manifestsmayincludeanyclassesinthemodulepathwhetherornotthey'relistedintheConsole.

Notes:

PuppetEnterprise3.7autodiscoversclasses,sothisstepisnolongerneeded.

Nodedeclarationsincodealwaysapply.ClassificationfromtheENCismergedinwithit.Seehttp://docs.puppetlabs.com/guides/external_nodes.html#how-merging-worksformoreinfo.

AddingaclasstotheConsole.

Fundamentalsv3.4.9 130 ©2015PuppetLabs

Page 131: Fundamentals Puppet

Exercise7.1:DeployYourModule

Objective:

Identifyhownodesareclassified.DeployyourmoduletothePuppetMaster.ClassifyandenforcetheconfigurationonyourAgent.

Notes:

Class-timeworkflow:

userdevelopscodeontheirownagentuservalidatescodewithparserandlintchecksuserapplies/enforcesstatelocallytosmoketestorverifytheirmoduleuserpushescodetothemaster,classifiesthenodeuser(optional)userchangessomethingabouttheagentsstateusertriggersanagentrunusingpuppet agent -t andconsumesreport

Exercise7.1:DeployYourModule

Fundamentalsv3.4.9 131 ©2015PuppetLabs

Page 132: Fundamentals Puppet

Checkpoint:Classification

Howdoesconfigurationstategetenforcedonagentnodes?

FollowingthemoduledirectorystructureallowsPuppettofindandloadclasseswhentheyaredeclared.

TrueFalse

Multiplenodedeclarationscanapplytoasinglenode.TrueFalse

Classifyinganodeornodegroupwithclassfoowill:applythecontentsofexamples/foo.pptothatnodeincludeclassfooonthenodeCopythemanifestfilesfromthefoomoduletothenodeandenforcethem

Nodescanbeclassifiedbyallofthefollowingmethods:The"global"nodedeclarationunconditionallyappliestoallnodesAnodedeclarationcanbedefinedwitharegexmatchagainstthenodenameIfnonodedeclarationmatches,thedefaultnodewillbeusedRulescanbedefinedintheConsoletoplacenodesintonodegroups.

Checkpoint:Classification

Fundamentalsv3.4.9 132 ©2015PuppetLabs

Page 133: Fundamentals Puppet

Resources

Resources

Fundamentalsv3.4.9 133 ©2015PuppetLabs

Page 134: Fundamentals Puppet

Lesson8:Resources

Objectives

Attheendofthislesson,youwillbeableto:

Identifyseveralkeyresourcetypes.Describethepurposeofaresource'stitleandnamevar.Explainwhyresourcessupportdifferentfeaturesondifferentplatforms.Discovernewresourcetypesandtheirattributes.

Lesson8:Resources

Fundamentalsv3.4.9 134 ©2015PuppetLabs

Page 135: Fundamentals Puppet

ResourceTypeListing

Displayalltheinstalledresourcetypes.

[root@training ~]# puppet describe --list

These are the types known to puppet:

anchor - A simple resource type intended to be used a ...

augeas - Apply a change or an array of changes to the ...

computer - Computer object management using DirectorySer ...

cron - Installs and manages cron jobs

exec - Executes external commands

file - Manages files, including their content, owner ...

file_line - Ensures that a given line is contained withi ...

filebucket - A repository for storing and retrieving file ...

firewall - This type provides the capability to manage ...

firewallchain - This type provides the capability to manage ...

group - Manage groups

host - Installs and manages host entries

ini_setting - .. no documentation ..

ini_subsetting - .. no documentation ..

interface - This represents a router or switch interface

java_ks - Manages entries in a java keystore

k5login - Manage the `.k5login` file for a user

macauthorization - Manage the Mac OS X authorization database

mailalias - .. no documentation ..

maillist - Manage email lists

mcx - MCX object management using DirectoryService ...

mount - Manages mounted filesystems, including puttin ...

nagios_command - The Nagios type command

nagios_contact - The Nagios type contact

...

Notes:

ThefirststepwhentryingtomanagesomethingwithPuppetistofigureoutwhatresourcetypetouse.Listouttheresourcetypesyou'vealreadygotinstalledandseeifthere'ssomethingthatmeetsyourneeds.Ifnot,thenyou'llsearchtheForgefortypes,suchasMySQLdatabasemanagement.Youwilloftenfindthattypestomanagetheresourcesyouneedhavealreadybeenwrittenforyou.

WewillcovertheForgecommunitysiteinalaterlesson.

ResourceTypeListing

Fundamentalsv3.4.9 135 ©2015PuppetLabs

Page 136: Fundamentals Puppet

ResourceTypeDocumentation

Usageinstructionsforeachtype.

[root@training ~]# puppet describe <type> [-s]

[root@training ~]# puppet describe --list

[root@training ~]# puppet doc -r type

Usethesamedocstringsusedtogeneratedocumentationpages.The-sflagprovidesatypesummaryonly.The--listargumentwilllistalltypesknowntoPuppet.puppet doccanoutputMarkdownorPDFfiles.

Weuseittogeneratedocs.puppetlabs.com.

Notes:

Anexampleofretrievingtheusagedocumentationfortheusertypeisshownbelow:

[root@training ~]# puppet describe user -s

user

====

Manage users. This type is mostly built to manage system

users, so it is lacking some features useful for managing normal

users.

This resource type uses the prescribed native tools for creating

...

OnlineversionsoftheResourceTypedocumentationcanbefoundat:http://docs.puppetlabs.com/references/latest/type.html

puppet doccanoutputdocumentationonallthingsPuppetbysimplypassinginthetypeofitemyouwantdocumented.

[root@training ~]# puppet doc -r [type|report|providers|...]

ResourceTypeDocumentation

Fundamentalsv3.4.9 136 ©2015PuppetLabs

Page 137: Fundamentals Puppet

OriginofResourceTypesSampleCoreResourceTypes

user

file

package

service

yumrepo

ResourceTypesmaycomefrommodules

file_line

ini_setting

java_ks

mysql_database

reboot

Notes:

ThePuppetForgeisagreatcommunitysiteforsharingmodules.You'llbeabletofindmodulesothershavewrittentomanagethingsasdisparateasLinuxsysctlsettingstotheNginxwebserverortheDrupalcontentmanagementsystem.

WewillexplorethePuppetForgeonDayThreeofthiscourse.

OriginofResourceTypes

Fundamentalsv3.4.9 137 ©2015PuppetLabs

Page 138: Fundamentals Puppet

ResourceTypeRelevanceCommontypesrunonallsupportedplatforms:

user

file

package

Platformspecifictypesrunonlyoncertainplatforms:

registry_value

yumrepo

zfs

Componentspecifictypesapplywhencertainsubsystemsareavailable:

augeas

selboolean

sshkey

ResourceTypeRelevance

Fundamentalsv3.4.9 138 ©2015PuppetLabs

Page 139: Fundamentals Puppet

ResourceLimitations

ProvidersarelimitedtofunctionalityexposedbytheOS.

Example:theuserResourceTypeProvider AllowDuplicates ManageHomedir ManagePasswords ManageSolarisRBAC

directoryservice ✓

hpxuseradd ✓ ✓

ldap ✓

netinfo ✓

pw ✓ ✓

user_role_add ✓ ✓ ✓ ✓

useradd ✓ ✓ ✓

windows_adsi ✓ ✓

Notes:

Forexample,onlytheSolarisuser_role_addproviderisabletomanageSolarisuserroles.

ResourceLimitations

Fundamentalsv3.4.9 139 ©2015PuppetLabs

Page 140: Fundamentals Puppet

Lab8.1:Findandusearesourcetype

Objective:

Determinetheresourcetypeusedtomanageahostrecord.Researchtheusageofthatresourcetype.Writeaclasstomanagethehostrecordandapplyittoyourmachine.

Lab8.1:Findandusearesourcetype

Fundamentalsv3.4.9 140 ©2015PuppetLabs

Page 141: Fundamentals Puppet

MetaResourceTypes

SometypesdonotdirectlymanagesomethingontheAgentsystem.

notify

Outputsaclientsidemessage.

resources

Canbeusedtosetdefaultparameterstootherresources.

schedule

Providesawaytoscheduleamanagementwindow.

Notes:

Thenotifyandscheduleresourcetypeswillbecoveredinthiscourse.Youmightbeinterestedintheresourcesresource,whichwillallowyoutosetdefaultparametersforotherresourcetypes.

Readaboutitathttp://docs.puppetlabs.com/references/latest/type.html#resources

MetaResourceTypes

Fundamentalsv3.4.9 141 ©2015PuppetLabs

Page 142: Fundamentals Puppet

notifyResourceType

OutputamessageontheAgent.DisplaysinlineforinteractivePuppetruns.IncludedinlogreportsforPuppetdaemonruns.

notify { 'This is the message being sent!': }

notify { 'another':

message => 'This is another message using the optional message parameter!',

}

Wanttolearnmore?

[root@training ~]# puppet describe notify

notifyResourceType

Fundamentalsv3.4.9 142 ©2015PuppetLabs

Page 143: Fundamentals Puppet

Metaparameters

Parametersthatworkwithanyresourcetype.

MetaparametersarepartofthePuppetframeworkitself.

alias:createsanaliasforaresourcenameaudit:auditresourceattributesnoop:tellstheresourcetotakenoactionloglevel:setsloglevelvaluetostandardsysloglevels

debug,info,notice,warning,err,alert,emerg,crit,verbose

schedule:setsascheduleforaresourcetobemanagedtag:setsatagforaresource

Notes:

Metaparametersareparametersthatworkwithanyresourcetype;theyarepartofthePuppetframeworkitselfratherthanbeingpartoftheimplementationofanygiveninstance.Thus,anydefinedmetaparametercanbeusedwithanyinstanceinyourmanifest,includingdefinedtypesthatyoucreate.

ForacompletelistofavailableMetaparameterspleasevisitPuppetDocs:http://docs.puppetlabs.com/references/latest/metaparameter.html

Metaparameters

Fundamentalsv3.4.9 143 ©2015PuppetLabs

Page 144: Fundamentals Puppet

Usingtheschedulemetaparameter.# The schedule resource type

schedule { 'daily maintenance window':

period => daily,

range => '20:00-22:00',

}

exec { '/usr/bin/apt-get update':

# The schedule metaparameter

schedule => 'daily maintenance window',

}

Thescheduleresourcecreatesawindowofopportunity.IfanAgentrunoccursinthiswindow,theresourcewillbeapplied.ThereisnoguaranteethatPuppetwillenforcetheresourceatthescheduledtime.

Wanttolearnmore?

[root@training ~]# puppet describe schedule

Notes:

Schedulesofhourly,daily,weekly,monthlyarecreatedautomatically.See:https://docs.puppetlabs.com/references/latest/type.html#schedule

Creatinganotherdailyscheduleallowsustospecifymoreparametersaboutit,suchasthetimewindowinwhichitshouldbeenforcedwithin.

Usingtheschedulemetaparameter.

Fundamentalsv3.4.9 144 ©2015PuppetLabs

Page 145: Fundamentals Puppet

Namevar

Specialattributethatidentifiesaresource.Forthepackageresourcetype,nameisthenamevar.

package { 'ssh':

ensure => present,

name => 'openssh-clients',

}

Forthefileresourcetype,pathisthenamevar.

file { 'sudoers':

ensure => file,

path => '/etc/sudoers',

source => 'puppet:///modules/sudo/sudoers',

}

Namevar

Fundamentalsv3.4.9 145 ©2015PuppetLabs

Page 146: Fundamentals Puppet

titleandnamevar

Servedifferentpurposes.

package { 'ssh':

ensure => present,

name => 'openssh-clients',

}

Thetitleofthisresourceis'ssh'.

ThisishowPuppetidentifiestheresourceinternally.Thetitleisoftenahuman-readabledescriptionoftheresource.

Thenameofthemanagedpackageis'openssh-clients'.

Thisisthenameofthepackageasthepackagemanagerseesit.

Thenamevarandtitlemustbothbeuniqueforanygivennode.

Notes:

Whenwelearnhowtomakereferencestootherresources,thepurposeofthehavinganamevaraswellasthetitlewillbecomemoreclear.

titleandnamevar

Fundamentalsv3.4.9 146 ©2015PuppetLabs

Page 147: Fundamentals Puppet

NamevarDefaults

Canbeomitted.namevardefaultstothesamevalueasthetitle.

# resource title is 'elvis' and manages a user named 'elvis'

user { 'elvis':

ensure => present,

gid => 'sysadmin',

}

Specifyingthenamevaroverridesthisdefault.

# resource title is 'Elvis Aaron Presley' and manages a user named 'theking'

user { 'Elvis Aaron Presley':

ensure => present,

name => 'theking',

gid => 'sysadmin',

}

Notes:

Omittingthenamevarisperfectlyappropriateinmostcases.Theabilitytonameresourcesinmultiplewaysbecomesvaluableasyourclassesbecomemorecomplex.

You'lloftenwanttousethisfunctionalitytoprovideshorternamesforyourresources,ratherthanoverlylongandverbose,likethisexample.

NamevarDefaults

Fundamentalsv3.4.9 147 ©2015PuppetLabs

Page 148: Fundamentals Puppet

fileResourceType

Managefiles,directories,orsymlinks.Managingafile:

file { '/etc/sudoers':

ensure => file,

owner => 'root',

group => 'root',

mode => '0440',

}

Whatdoesthismanifesttellusaboutthecontentsof/etc/sudoers?

Managingadirectory:

file { '/etc/openldap':

ensure => directory,

mode => '0755',

}

Notes:

Thestateofafileresourcecanbeabsent,file,directory,orlink.YoushouldneverusepresentforafileresourcebecausethatinstructsPuppettonotcareaboutthedifference.

Inacoupleslides,we'lldemonstratehowyoucanmanagethecontentsofafile.

fileResourceType

Fundamentalsv3.4.9 148 ©2015PuppetLabs

Page 149: Fundamentals Puppet

FileResourceAttributespath:Specifiesthetargetlocationforfile.ensure:absent,file,directory,orlink.owner:Owneroffile.group:Groupoffile.mode:Modeoffile.content:Specifiesthefilecontentasastring.source:Specifiesthesourceoffile(eitherpuppetmasterorlocal).target:Specifythetargetofasymlink.

Wanttoknowmore?

[root@training ~]# puppet describe file

Notes:

Notethatcontent,source,andtargetaremutuallyexclusive.

FileResourceAttributes

Fundamentalsv3.4.9 149 ©2015PuppetLabs

Page 150: Fundamentals Puppet

FileContent

Specifyingfilecontentasastring.

file { '/etc/motd':

ensure => file,

owner => 'root',

group => 'root',

mode => '0644',

content => "Think before you type\n",

}

Youcanmanagefilecontentbydirectlyspecifyingitinthecontentattribute.

Notes:

Wewillcovertemplatesinanotherpartofthecourse.Templatescanbeusedtodynamicallygeneratefilesandseparatethelogicofyourclassfromthepresentationofthefile.

FileContent

Fundamentalsv3.4.9 150 ©2015PuppetLabs

Page 151: Fundamentals Puppet

FileSource

Provideasourcelocationforafile.

file { '/etc/sudoers':

ensure => file,

owner => 'root',

group => 'root',

mode => '0440',

source => 'puppet:///modules/sudo/sudoers',

}

Youcanmanagefilecontentbydistributingitfromamodule.

[root@training ~]# tree /etc/puppetlabs/puppet/environments/production/modules/sudo/

├── files│ └── sudoers

[root@training ~]# cd /etc/puppetlabs/puppet/environments

[root@training environments]# cat production/modules/sudo/files/sudoers

## Sudoers allows particular users to run various commands as

## the root user, without needing the root password.

##

...

...

%wheel ALL=(ALL) NOPASSWD: ALL

Notes:

Thesourceparameterletsyouincludeastaticfileinyourmodulethatwillbesyncedouttoagentsrequestingit.IfthefileontheAgentdoesn'tmatchthefileinthemoduleontheMaster,thenPuppetwillcopyoverit.Thisismostusefulforfilesthatwillbeexactlythesameonmanyorallclientmachines.

ThefileisnottransferredeachtimetheAgentruns.MD5sumsofthefileasitexistsontheclientandonthemasterarecalculatedandcompared.Iftheydiffer,thentheAgentsyncsthefile.

FileSource

Fundamentalsv3.4.9 151 ©2015PuppetLabs

Page 152: Fundamentals Puppet

FileServingFunctionality

Thepuppet:///URIdescribeswherethefileshouldcomefrom.puppet://[source]/<mountpoint>/<module>/<file path>

[source]defaultstowhereverthecatalogcamefrom.Usuallyleftblank.<mountpoint>ofmodulesinstructsPuppettosearchthemodulepath.<module>isthenameofthemoduletolookfor.<file path>isthepathtoafilewithinthatmodules'sfilesdirectory

[root@training ~]# tree /etc/puppetlabs/puppet/environments/production/modules/sudo/

├── files│ ├── sudoers ## source => 'puppet:///modules/sudo/sudoers',│ └── sudoers.d│ └── admins ## source => 'puppet:///modules/sudo/sudoers.d/admins',├── manifests └── init.pp ## class sudo { ... }

Notes:

ThesourceshouldbespecifiedasthehostnameofaPuppetmastertoretrievethefilefrom.Thefileisonlytransferredifit'snotthesameaswhat'salreadyondisk.

Thesourcedefaultstowherethecatalogcamefromandisnormallyomitted.Thismeansthatifyourunpuppet applyonasmoketestmanifest,thatthesameURIwillretrievethefilefromyourlocaldisk.

FileServingFunctionality

Fundamentalsv3.4.9 152 ©2015PuppetLabs

Page 153: Fundamentals Puppet

FileSymlinks

Manageasymlinktoanotherfile.Asymboliclinkcanprovideanaliaspointingtoanotherfile.Ineffect,we'llendupwithtwonamesforafile.Supportedonallmodernoperatingsystems.

class sysinfo {

file { '/etc/custom-release':

ensure => file,

source => 'puppet:///modules/sysinfo/system-release',

}

file { '/etc/system-release':

ensure => link,

target => '/etc/custom-release',

}

...

}

FileSymlinks

Fundamentalsv3.4.9 153 ©2015PuppetLabs

Page 154: Fundamentals Puppet

IntrotoDeployingnginxLabsIntroduction

Wewillbuildasimplemoduletomanagethenginxwebserveronournodesanditerativelyimproveitintointoacompletesolutiontomanagetheserviceondifferentplatformsacrossourentireinfrastructure.

Objectives

Overseverallabsyouwill:

Deployannginxwebservice.Serveanindexpagewithserverinformation.Programaticallybuildwebpagesfromtemplates.Instantiateseveralvirtualhosts.Identifyplatformdifferencesanddesignabstractionsforthem.

IntrotoDeployingnginxLabs

Fundamentalsv3.4.9 154 ©2015PuppetLabs

Page 155: Fundamentals Puppet

Lab8.2:Package|File|Service

Objective:

WritePuppetcodetomanageinstallationofthenginxwebserverpackage.

Lab8.2:Package|File|Service

Fundamentalsv3.4.9 155 ©2015PuppetLabs

Page 156: Fundamentals Puppet

TheserviceResourceservice { 'sshd':

ensure => running,

enable => true,

}

serviceResourceAttributes:restart:Specifyarestartcommand.start:Specifyastartcommand.status:Specifyastatuscommand.stop:Specifyastopcommand.pattern:Thepatterntosearchforintheprocesstable.

Wanttolearnmore?

[root@training ~]# puppet describe service

TheserviceResource

Fundamentalsv3.4.9 156 ©2015PuppetLabs

Page 157: Fundamentals Puppet

TheexecResource

Executesexternalcommandsontheclient.

exec { 'updatedb':

path => '/usr/bin',

creates => '/var/lib/mlocate/mlocate.db',

}

Execresourcesshouldbeavoidedwhenpossiblebecause:

effectsarenottransparent.youareresponsibleforidempotency.troubleshootingismoredifficult.

Wanttolearnmore?

[root@training ~]# puppet describe exec

TheexecResource

Fundamentalsv3.4.9 157 ©2015PuppetLabs

Page 158: Fundamentals Puppet

Checkpoint:Resources

HowdoesPuppetuseresourcetypestomanageconfiguration?

Resourcetypessometimesapplyonlyoncertainplatforms.TrueFalse

Resourcetypesofferexactlythesamefunctionalityonallsupportedplatforms.TrueFalse

Resourcemetaparametersmustbedefinedbyeachresourcetypewhichimplementsthem.TrueFalse

Theschedulemetaparametermusthaveacorrespondingscheduleresourcetobeuseful.TrueFalse

Thepuppetdescribecommandwill:ShowthelistofattributesthattheresourcetypescanmanageProvideasummarydescriptionoftheresourcetypeDescribethesyntaxrequiredforusingtheresourcetypeInstalltherequestedmoduleintoyourmodulepath

Checkpoint:Resources

Fundamentalsv3.4.9 158 ©2015PuppetLabs

Page 159: Fundamentals Puppet

ResourceRelationships

ResourceRelationships

Fundamentalsv3.4.9 159 ©2015PuppetLabs

Page 160: Fundamentals Puppet

Lesson9:ResourceRelationships

Objectives

Attheendofthislesson,youwillbeableto:

EstablishdependenciesbetweenPuppetResources.UsePuppettorestartaservicewhenitsdependencieschange.UsethePackage|File|Servicedesignpattern.

Lesson9:ResourceRelationships

Fundamentalsv3.4.9 160 ©2015PuppetLabs

Page 161: Fundamentals Puppet

DependencyManagement

HowdoesPuppetprioritizetheenforcementofresources?Puppetdoesnotenforceresourcestopdown,basedontheirpositioninthemanifest.Instead,Puppetchecksforapplicabledependenciesbetweenresourcesinthemanifestcode.Puppetthenreordersresourceenforcementtomeetthedeterminedrelationshiprequirements.

Manifestsareparsedinsourceorderwhencompiling,

buttheresourceenforcementorderisdrivenbythedependencygraph.

Notes:

NotethatPuppetEnterpriserecentlyenabledtheoptionofsourcebasedordering.Thisdoesnotreplaceunderstandingthedependencysystem,andwillbecoveredtowardtheendofthesection.

DependencyManagement

Fundamentalsv3.4.9 161 ©2015PuppetLabs

Page 162: Fundamentals Puppet

Relationships

Definedwithmetaparameters.Explicitlydefineorderingrelationships.Metaparametersworkwithallresourcetypes.Therearefourmetaparameters:

representingtwodifferentkindsofrelationshipsbetweenresources.

Notes:

Fourmetaparametersthatestablishrelationshipsbetweenresourceswillbecoveredfurther:requirebeforesubscribenotify

Bestpracticesaretoalwaysdefinethedependencyrelationshipsyouneed,andtoneverdefinetherelationshipsthatyoudon't.

Relationships

Fundamentalsv3.4.9 162 ©2015PuppetLabs

Page 163: Fundamentals Puppet

require

requireareferencedresourcetobeappliedfirst.

require

Fundamentalsv3.4.9 163 ©2015PuppetLabs

Page 164: Fundamentals Puppet

Example:require

Ensurethatsshdisstartedafteropensshisinstalled.

package { 'openssh':

ensure => present,

}

service { 'sshd':

ensure => running,

enable => true,

require => Package['openssh'],

}

Example:require

Fundamentalsv3.4.9 164 ©2015PuppetLabs

Page 165: Fundamentals Puppet

ReferenceSyntax

Referenceexistingresourcesinyourcatalog.

Type['title']

forexample:

Package['openssh']

Theuppercaseindicatesareferencetoaresourcetype.Thepartinbraces"indexes"tothetitleofaresource.

Notes:

PuppetResourcesalwaysgetspecifiedinpairs:Typeandtitle.

Whenwemakereference,weneedbothparts

Whenreferencingexistingresourcesfromyourcatalog,makesure:

Thefirstcharacterofthetypeiscapitalized.Theresourcetitlegoesintothesquarebraces.

ReferenceSyntax

Fundamentalsv3.4.9 165 ©2015PuppetLabs

Page 166: Fundamentals Puppet

before

Requesttobeappliedbeforeareferencedresource.

before

Fundamentalsv3.4.9 166 ©2015PuppetLabs

Page 167: Fundamentals Puppet

Example:before

Alsoensurethatsshdisstartedafteropensshisinstalled.

package { 'openssh':

ensure => present,

before => Service['sshd'],

}

service { 'sshd':

ensure => running,

enable => true,

}

Notes:

Noticethattherequiremetaparameterhasbeenmovedfromtheserviceresourcetoabeforemetaparameteronthepackageresource.

Thishasexactlythesameeffectasthepreviousrequirestatementdid.requireandbeforesimplydefineeitherendofthatsamerelationship.There'snofunctionaldifferencebetweenthem;youcansimplychoosewhichonefitsyourcurrentneedsbetter.

Example:before

Fundamentalsv3.4.9 167 ©2015PuppetLabs

Page 168: Fundamentals Puppet

RefreshEvents

Resourcechangescanrefreshotherresources.subscribeandnotifymetaparametersestablishrefreshrelationships.Thespecificresponsetoarefreshisresourcespecific.

Restartaservice.Alterthewayanexeccommandexecutes.Remountavolume.RebootaWindowscomputerafterupdates.

Notes:

service,mount,andexecaretheonlybuiltintypesthatexplicitlyrespondtorefreshevents.ThirdpartymodulesfromtheForgemayrespondtorefreshevents.TheWindowsreboottype(installedbydefaultwithPuppetEnterprise)usestherefresheventtoscheduleasystemrebootduringaPuppetrun.

RefreshEvents

Fundamentalsv3.4.9 168 ©2015PuppetLabs

Page 169: Fundamentals Puppet

subscribe

ListenforPuppetchangestothereferencedresource.

subscribe

Fundamentalsv3.4.9 169 ©2015PuppetLabs

Page 170: Fundamentals Puppet

RefreshingServicesRestartsshdifPuppetchanges/etc/ssh/sshd_config.

file { '/etc/ssh/sshd_config':

ensure => file,

source => 'puppet:///modules/ssh/sshd_config',

}

service { 'sshd':

ensure => running,

enable => true,

subscribe => File['/etc/ssh/sshd_config'],

}

Thesubscribemetaparameterimpliesrequire.Enforcesorderaswellaswatchingforchanges.OnlysendsrefresheventswhenPuppetmakeschanges.

RefreshingServices

Fundamentalsv3.4.9 170 ©2015PuppetLabs

Page 171: Fundamentals Puppet

notify

SendnotificationswhenPuppetchangesthecontainingresource.

notify

Fundamentalsv3.4.9 171 ©2015PuppetLabs

Page 172: Fundamentals Puppet

RefreshingServicesAlsorestartssshdifPuppetchanges/etc/ssh/sshd_config.

file { '/etc/ssh/sshd_config':

ensure => file,

source => 'puppet:///modules/ssh/sshd_config',

notify => Service['sshd'],

}

service { 'sshd':

ensure => running,

enable => true,

}

Themetaparameternotifyimpliesbefore.Enforcesorderaswellassendingchangenotifications.OnlysendsrefresheventswhenPuppetmakeschanges.

RefreshingServices

Fundamentalsv3.4.9 172 ©2015PuppetLabs

Page 173: Fundamentals Puppet

Review

UnderstandingResourceRelationships-Part1

WhichresourcedoesPuppetmanagefirst?

file { '/etc/ntp.conf':

ensure => file,

owner => 'root',

group => 'root',

mode => '0644',

source => 'puppet:///modules/ntp/ntp.conf',

require => Package['ntp'],

}

package { 'ntp':

ensure => present,

}

service { 'ntpd':

ensure => running,

enable => true,

subscribe => File['/etc/ntp.conf'],

}

Whathappensif/etc/ntp.confchanges?

Review

Fundamentalsv3.4.9 173 ©2015PuppetLabs

Page 174: Fundamentals Puppet

Review

UnderstandingResourceRelationships-Part2

WhichresourcedoesPuppetmanagefirst?

file { '/etc/ntp.conf':

ensure => file,

owner => 'root',

group => 'root',

mode => '0644',

source => 'puppet:///modules/ntp/ntp.conf',

notify => Service['ntpd'],

}

service { 'ntpd':

ensure => running,

enable => true,

}

package { 'ntp':

ensure => present,

before => File['/etc/ntp.conf'],

}

Whathappensif/etc/ntp.confchanges?

Notes:

Rememberthatrequireandbeforespecifyeitherendofthesamerelationship,asdosubscribeandnotify.Theyareexactlyequivalent.Thechoicebetweenthemissimplywhichismoreconvenientandmorereadable.

Forexample,sayyouhave9filesand1service.

Option1-theservicesubscribestothe9filesOption2-the9fileseachnotifytheservice

Option1requireslesscodeandmaybemorereadable.

Review

Fundamentalsv3.4.9 174 ©2015PuppetLabs

Page 175: Fundamentals Puppet

Package|File|Service

Oneofthemostusefulandcommondesignpatternsusedinproduction.

Wecommonlyspecifyseveralresourcestogethertomodelacompleteconfiguration.Areasonableworkflowwheninstallingaserviceisto:

1. Installapackage.2. Configureoneormoreconfigfiles.3. Enabletheservice.

TomodelthisinPuppet,weusethePackage|File|Servicedesignpattern.

Package|File|Service

Fundamentalsv3.4.9 175 ©2015PuppetLabs

Page 176: Fundamentals Puppet

First

InstallaPackage

package { 'ntp':

ensure => present,

}

First

Fundamentalsv3.4.9 176 ©2015PuppetLabs

Page 177: Fundamentals Puppet

Second

ConfigureaFile

package { 'ntp':

ensure => present,

}

file { '/etc/ntp.conf':

ensure => file,

owner => 'root',

group => 'root',

mode => '0644',

source => 'puppet:///modules/ntp/ntp.conf',

require => Package['ntp'],

}

Whydoes/etc/ntp.confneedtobeconfiguredafterthepackageisinstalled?

Notes:

Iftheconfigfilewasconfiguredbeforethepackagewasinstalled,it'spossiblethatthepackageinstallationwouldoverwriteit.Toavoidthat,weensurethatpackageinstallationhappensfirst,thenweoverwriteanysampleordefaultconfigurationwiththeexpectedconfigurationwe'dlike.

Second

Fundamentalsv3.4.9 177 ©2015PuppetLabs

Page 178: Fundamentals Puppet

Third

EnableaService

package { 'ntp':

ensure => present,

}

file { '/etc/ntp.conf':

ensure => file,

owner => 'root',

group => 'root',

mode => '0644',

source => 'puppet:///modules/ntp/ntp.conf',

require => Package['ntp'],

}

service { 'ntpd':

ensure => running,

enable => true,

subscribe => File['/etc/ntp.conf'],

}

Thentpdserviceresourceissubscribingtothe/etc/ntp.conffileresource.ItwillrestartwhenPuppetmodifiestheconfigfile.Whynotalsosubscribetothepackageresource?

Notes:

Inmanycases,thepackagemanagerand/orpackagewillscheduleitsassociatedservicestostoppriortoupgradeandrestartafterwards.Inthatcase,ifwesubscribedtothepackageresource,we'denduprestartingtheserviceagain.

Iftheserviceisnotautomaticallyrestarted,thenitwouldbeusefultosubscribetothepackageresource.

Third

Fundamentalsv3.4.9 178 ©2015PuppetLabs

Page 179: Fundamentals Puppet

Workflowrecap:

1. Installpackage.

2. Configurefile.

3. Enableservice.

4. Restartservicewhenconfigfileisupdated.

Workflowrecap:

Fundamentalsv3.4.9 179 ©2015PuppetLabs

Page 180: Fundamentals Puppet

ReferenceSyntaxRoundup

Aresourceinamanifestcorrespondstoaresourceonthenodeit'sappliedto.

ReferenceSyntaxRoundup

Fundamentalsv3.4.9 180 ©2015PuppetLabs

Page 181: Fundamentals Puppet

ReferenceSyntaxRoundup

Areferenceinamanifestpointstoanotherresourceinthecatalog...

ReferenceSyntaxRoundup

Fundamentalsv3.4.9 181 ©2015PuppetLabs

Page 182: Fundamentals Puppet

ReferenceSyntaxRoundup

...whichmayormaynotcompletelyrepresentthestateofthenode.

ReferenceSyntaxRoundup

Fundamentalsv3.4.9 182 ©2015PuppetLabs

Page 183: Fundamentals Puppet

SyntaxRoundupDeclaringaresource:

type { 'title':

attribute => value,

}

Referencingaresource:

Type['title']

Definingaclassofresources:

class classname {

...

}

SyntaxRoundup

Fundamentalsv3.4.9 183 ©2015PuppetLabs

Page 184: Fundamentals Puppet

SyntaxRoundupDefiningaclass:

class ssh {

# Declaring a Resource

package { 'openssh-server':

ensure => present,

}

# Declaring a Resource and Referencing Another

file { '/etc/ssh/sshd_config':

ensure => present,

require => Package['openssh-server'],

}

}

Declaringaclass:

include ssh

SyntaxRoundup

Fundamentalsv3.4.9 184 ©2015PuppetLabs

Page 185: Fundamentals Puppet

DependencyShortcuts

Specifyingeachandeverydependencycanbetedious.Implicitdependencies:

Certainresourcesalwaysdependononeanother.Automaticsoftdependenciesfortheserelatedresources.

Manifestordering:

Ifexplicitdependenciesarenotprovided,Puppetwillenforceresourcesintheordertheyappearinthemanifest.Onlyapplieswithinasinglemanifestfile.Supercededbyanyotherdependencies(anywhereinthecodebase).NotavailableonolderversionsofPuppet.

Notes:

Allsoftrelationshipsaresupersededbyexplicitrelationshipdeclarations.ManifestorderinghasbeenanoptionsincePuppet3.3.0andonbydefaultsincePuppetEnterprise3.3andPuppet4.0.

Manifestorderingappliesonlytoresourcesthataren'texplicitlyorderedandcannotbeexpectedtoworkdeterminatelyacrossmultiplefiles.Relyingonthishiddenorderingisagoodwaytocreatemodulesthatbreakinunexpectedfashionsonmachinesthatdon'thaveitenabledorthatincludedifferentclassesorincludetheminadifferentorder.

Bestpracticesaretoexplicitlydefineallrequiredresources,evenwhenusingmanifestordering.

DependencyShortcuts

Fundamentalsv3.4.9 185 ©2015PuppetLabs

Page 186: Fundamentals Puppet

UsersandGroupsExplicitlyassigneddependency:

user { 'elvis':

ensure => present,

home => '/home/elvis',

managehome => true,

uid => '5000',

gid => 'hounddog',

shell => '/bin/bash',

require => Group['hounddog'], # redundant!

}

group { 'hounddog':

ensure => present,

gid => '5000',

}

UsersandGroups

Fundamentalsv3.4.9 186 ©2015PuppetLabs

Page 187: Fundamentals Puppet

UsersandGroupsPuppetimplicitlyordersusersandgroups:

user { 'elvis':

ensure => present,

home => '/home/elvis',

managehome => true,

uid => '5000',

gid => 'hounddog',

shell => '/bin/bash',

}

group { 'hounddog':

ensure => present,

gid => '5000',

}

UsersandGroups

Fundamentalsv3.4.9 187 ©2015PuppetLabs

Page 188: Fundamentals Puppet

FilesandDirectoriesThedirectorymustexistbeforethefilecanbecreated:

file { '/etc/httpd/conf.d':

ensure => directory,

owner => 'root',

group => 'root',

mode => '0755',

}

file { '/etc/httpd/conf.d/www.puppetlabs.com.conf':

ensure => file,

owner => 'root',

group => 'root',

mode => '0644',

content => "# This file configures the puppetlabs.com website\n",

require => File['/etc/httpd/conf.d'], # not required

}

FilesandDirectories

Fundamentalsv3.4.9 188 ©2015PuppetLabs

Page 189: Fundamentals Puppet

FilesandDirectoriesPuppetimplicitlyrecognizesfilehierarchy:

file { '/etc/httpd/conf.d':

ensure => directory,

owner => 'root',

group => 'root',

mode => '0755',

}

file { '/etc/httpd/conf.d/www.puppetlabs.com.conf':

ensure => file,

owner => 'root',

group => 'root',

mode => '0644',

content => "# This file configures the puppetlabs.com website\n",

}

FilesandDirectories

Fundamentalsv3.4.9 189 ©2015PuppetLabs

Page 190: Fundamentals Puppet

FileOwnershipImplicitrelationshipsbetweenfileownershipanduserresources:

user { 'elvis':

ensure => present,

home => '/home/elvis',

managehome => true,

uid => '5000',

gid => 'hounddog', # implicitly requires Group['hounddog']

shell => '/bin/bash',

}

group { 'hounddog':

ensure => present,

gid => '5000',

}

file { '/etc/graceland':

ensure => file,

owner => 'elvis', # implicitly requires User['elvis']

group => 'hounddog', # implicitly requires Group['hounddog']

mode => '0644',

content => 'Graceland is a happy home.',

}

FileOwnership

Fundamentalsv3.4.9 190 ©2015PuppetLabs

Page 191: Fundamentals Puppet

Lab9.1:Package|File|Service

Objective:

Extendyournginxmoduletoensurethatthenginxserviceisrunningandisrestartedasrequired.

Lab9.1:Package|File|Service

Fundamentalsv3.4.9 191 ©2015PuppetLabs

Page 192: Fundamentals Puppet

Checkpoint:Relationships

HowdoesPuppethandledependenciesbetweenresources?

SubscribingtoafileondiskmeansthatPuppetwillrunanytimethatfilechanges.TrueFalse

Youcanrequireanyof:Usersthatexistonthenode,aslongastheyaresystemusersFilesinstalledbyRPMorDebianpackagesAnyresourcesthatexistinthecatalogAresourcethatwasmanagedbyanearlierPuppetrun.

Refresheventspropagatedbyanotifyorsubscribecan:RestartaserviceRunanexeccommandagainDeleteandrewriteafile

Implicitrelationshipsexistbetween:ServicesandthepackagesthatinstallthoseservicesUserandgroupownershipoffilesPackagesandsystemusersinstalledbythepackagesFilescontainedinsideofdirectories

Checkpoint:Relationships

Fundamentalsv3.4.9 192 ©2015PuppetLabs

Page 193: Fundamentals Puppet

LanguageConstructs

LanguageConstructs

Fundamentalsv3.4.9 193 ©2015PuppetLabs

Page 194: Fundamentals Puppet

Lesson10:LanguageConstructs

Objectives

Attheendofthislesson,youwillbeableto:

UsevariablesinPuppet'sdomainspecificlanguage(DSL).UsearraysinPuppet'sDSL.UseconditionallogicexpressionsintheDSL.CreateaPuppetmanifestthatiscapableofworkingonmultipleOperatingSystems.

Lesson10:LanguageConstructs

Fundamentalsv3.4.9 194 ©2015PuppetLabs

Page 195: Fundamentals Puppet

VariablesVariablesareprefixedwith'$':

$httpd_dir = '/etc/httpd/conf.d'

Variablescanbeusedasresourcetitles:

file { $httpd_dir:

ensure => directory,

}

Variablescanbeusedasattributevalues:

file { '/etc/httpd/conf.d/README':

ensure => file,

content => $readme_content,

}

Notes:

Variablesmustbedefinedbeforetheycanbeused.BecausethePuppetDSLallowsyoutoreferenceundefinedvariables,thisisacommonsourceoferrors.Ifthe$readme_contentvariableweretobedefinedafterthefileresourcewasdeclared,thefilewouldbecreatedwithnocontent.

Variables

Fundamentalsv3.4.9 195 ©2015PuppetLabs

Page 196: Fundamentals Puppet

ConstructingStringsSingle-quotedstringsareliteralstrings:

$string = 'My httpd_dir is ${httpd_dir}\n'

> My httpd_dir is ${httpd_dir}\n

Double-quotedstringsallowsvariableinterpolation.

Variablesinstringsshouldbebracketedwith{}forclarity:

$string = "My httpd_dir is ${httpd_dir}\n"

> My httpd_dir is /etc/httpd/conf.d

Notes:

Variablesshouldbeenclosedincurlybraceswhentheyarebeinginterpolated,suchaswhentheyarepartofastringinsidedoublequotationmarks.Curlybracesshouldnotbeusedoutsideofstrings.

ConstructingStrings

Fundamentalsv3.4.9 196 ©2015PuppetLabs

Page 197: Fundamentals Puppet

VariablesExampleUsingvariablesjudiciouslywillreducerepetitioninyourcode.

class apache {

$httpd_dir = '/etc/httpd/conf.d'

file { $httpd_dir:

ensure => directory,

}

file { "${httpd_dir}/www1.conf":

ensure => file,

content => "Configuring the ${httpd_dir}/www1.conf",

}

}

Notes:

Usingavariablelikethismeansthatyoucanmakeupdatesinasingleplaceandtheyarepropagatedthroughoutyourcodebase.Acommonpracticeistoputthesevariableassignmentsintoaparamsclass,suchasmymodule::params,andthenincludethatclassandrefertothefullyscopednameanywhereit'sneeded.Scopewillbecoveredinthenextfewslides.

VariablesExample

Fundamentalsv3.4.9 197 ©2015PuppetLabs

Page 198: Fundamentals Puppet

VariablesareimmutableVariablesCANNOTbereassigned!

class apache {

$httpd_dir = '/etc/httpd/conf.d'

file { $httpd_dir:

ensure => directory,

}

# Compilation will fail at the reassignment of $httpd_dir

$httpd_dir = '/etc/site/httpd/conf.dir'

file { $httpd_dir:

ensure => directory,

}

}

Notes:

Variablescannotbereassigned,butlocalvariablesofthesamenamecanbesettooverrideglobalvariables,includingfacts.

ImmutableUnchangingovertimeorunabletobechanged.

Variablesareimmutable

Fundamentalsv3.4.9 198 ©2015PuppetLabs

Page 199: Fundamentals Puppet

Scope

Partialisolationofareasofcode.

Notes:

Scopelimitsthereachofvariables.Anygivenscopehasaccesstoitsowncontents,andalsoreceivesadditionalcontentsfromthenodeandfromtopscope.

Topscopeisusuallydefinedbysite.pp,outsideofanynodedefinitions.Nodescopeiswithinthedefinitionofthecurrentnode.Classscopeiswithinthedefinitionoftheclass.

DetailsonscopecanbefoundinPuppetDocumentationathttp://docs.puppetlabs.com/puppet/2.7/reference/lang_scope.html.

Scope

Fundamentalsv3.4.9 199 ©2015PuppetLabs

Page 200: Fundamentals Puppet

VariableScope

Availabilityofvariablesisdictatedbythevariable'sscope.Localscopelocallyoverridesvariablesofthesamenamefromtheparent.

class apache::params {

$logroot = '/var/log/httpd'

[...]

}

class apache::logs {

include apache::params

$logroot = $apache::params::logroot

file { "${logroot}/httpd.log":

ensure => file,

owner => 'apache',

group => 'apache',

}

}

Out-of-scopevariablesfromnamedscopescanbeaccessedbyusingtheirqualifiednamesiftheirparentisincluded.Thenameoftopscopeisanemptystring.Factsaretopscope(global)variables.

Notes:

Bestpracticesaretoincludereferencedclasseswhenyouneedthem.Theincludefunctionisidempotent,soitcanbecalledmanytimeswithoutharm.Thiswillensurethatthereferencedvariablesarealwaysavailable.

DetailsonvariablescopecanbefoundinPuppetDocumentationathttp://docs.puppetlabs.com/puppet/latest/reference/lang_variables.html#scope.

VariableScope

Fundamentalsv3.4.9 200 ©2015PuppetLabs

Page 201: Fundamentals Puppet

FactsareGlobalVariables

Notethedoublecolonscopeoperator.

class apache {

$httpd_dir = '/etc/httpd/conf.d'

file { $httpd_dir:

ensure => directory,

}

file { "${httpd_dir}/www1.conf":

ensure => file,

content => "Configuring the ${httpd_dir}/www1.conf for ${::hostname}\n",

}

}

Theemptystringbeforethe::scopeoperatorindicatestopscope.

Notes:

Factsareglobalvariablesandthereforecanbeusedinyourmanifests.InPuppetglobal,variablesaredenotedby"::"beforethename.

Bestpracticesaretoalwaysincludetheempty::scopeoperatorwhenreferringtofacts.Thismakesitexplicitwhichvariableyou'rereferringtoandmakeserrorslesslikelyifyouhappentohaveafactandlocalvariableofthesamename.

FactsareGlobalVariables

Fundamentalsv3.4.9 201 ©2015PuppetLabs

Page 202: Fundamentals Puppet

ResourceDefaults

Puppetallowsyoutodeclareresourcedefaults.

class apache {

File {

owner => 'root',

group => 'root',

mode => '0644',

}

$httpd_dir = '/etc/httpd/conf.d'

file { $httpd_dir:

ensure => directory,

}

file { "${httpd_dir}/www1.conf":

ensure => file,

content => "Configuring the ${httpd_dir}/www1.conf for ${::hostname}\n",

}

}

Puppetpromotesamodedefaultof0644tomode0755fordirectories.Resourcedefaultsaffectallresourceswithincurrentscope.

Notes:

Puppetgroupsthereadbitandthetraversebitfordirectories,whichisalmostalwayswhatisactuallywanted.Theideaistoallowmanagingwholedirectoriesasmode0644withoutmakingallthedirectoryfilesexecutable.

ResourceDefaults

Fundamentalsv3.4.9 202 ©2015PuppetLabs

Page 203: Fundamentals Puppet

ResourceDefaultsExampleCutandpastedcodehasrepetition,makingupdatestedious.Codeislongerandlessreadable.Difficulttoseedifferencesbetweenresources.

file { '/etc/httpd/conf.d':

ensure => directory,

owner => 'root',

group => 'root',

mode => '0755',

}

file { '/etc/httpd/conf.d/www.puppetlabs.com.conf':

ensure => file,

owner => 'webadmin',

group => 'root',

mode => '0644',

content => "# This file configures the puppetlabs.com website\n",

}

file { '/etc/httpd/conf.d/docs.puppetlabs.com.conf':

ensure => file,

owner => 'root',

group => 'root',

mode => '0644',

content => "# This file configures the docs website\n",

}

ResourceDefaultsExample

Fundamentalsv3.4.9 203 ©2015PuppetLabs

Page 204: Fundamentals Puppet

ResourceDefaultsExampleAbstractoutcommonattributes.Codebecomesshorterandmorereadable.Obviouswhichattributesdifferbetweenresources.

File {

owner => 'root',

group => 'root',

mode => '0644',

}

file { '/etc/httpd/conf.d':

ensure => directory,

}

file { '/etc/httpd/conf.d/www.puppetlabs.com.conf':

ensure => file,

owner => 'webadmin',

content => "This file configures the puppetlabs.com site\n",

}

file { '/etc/httpd/conf.d/www.conf':

ensure => file,

content => "This file configures the docs site\n",

}

Notes:

Resourcedefaultsrarelyincludetheensureattribute,especiallyforresourcetypeswithimplicitensurevalues.It'smoreexplicitandmorereadabletodescribethetypeoffileresourceweexpectdirectlywiththeresourcedeclarationitself,ratherthanrequiringthereadertobacktracktothedefaulttodeterminewhethertheresourcetypedescribesafileordirectory.

ResourceDefaultsExample

Fundamentalsv3.4.9 204 ©2015PuppetLabs

Page 205: Fundamentals Puppet

ArraysThePuppetlanguagesupportssimplearrays:

$somearray = [ 'one', 'two', 'three' ]

Arrayscanbeusedasanargumenttosomeresourceparameters:

user { 'elvis':

ensure => present,

home => '/home/elvis',

uid => '5000',

gid => 'hounddog',

shell => '/bin/bash',

groups => ['jailhouse', 'surfer', 'legend'],

}

Arrays

Fundamentalsv3.4.9 205 ©2015PuppetLabs

Page 206: Fundamentals Puppet

ArraysinTitlesArrayscanalsobeusedasthetitleforresources:

file { ['/tmp/one', '/tmp/one/two', '/tmp/one/two/three']:

ensure => directory,

owner => 'root',

group => 'root',

mode => '0750',

}

Thiscreatesthreeuniquefileresources.

Theydifferonlyintitle.Theycanbereferredtoindividually.Theyaretreatedasindividualresources.

require => File['/tmp/one/two']

ArraysinTitles

Fundamentalsv3.4.9 206 ©2015PuppetLabs

Page 207: Fundamentals Puppet

ArraysasParametersArrayscanbeargumentstoparameters:

service { 'syslog':

ensure => running,

enable => true,

require => [ File['/etc/rsyslog.conf'], Package['rsyslog'] ],

}

ArraysasParameters

Fundamentalsv3.4.9 207 ©2015PuppetLabs

Page 208: Fundamentals Puppet

Lab10.1:CodeSimplification

Objective:

Identifycommmonparametersamongresourcetypes.Useresourcedefaultstosimplifyyourmodule.

Lab10.1:CodeSimplification

Fundamentalsv3.4.9 208 ©2015PuppetLabs

Page 209: Fundamentals Puppet

ConditionalExpressionsPuppetsupportsfourconditionalexpressions:Theseconditionalscanbedividedintotwotypes:

Conditionalswhichreturnavalue

Selectors

Conditionalswhichalterlogicflow

Casestatementsifstatementsunlessstatements

ConditionalExpressions

Fundamentalsv3.4.9 209 ©2015PuppetLabs

Page 210: Fundamentals Puppet

SelectorValues

Thevaluereturnedbyaselectorcanbeused:

in-statement

package { 'ssh':

ensure => present,

name => $::operatingsystem ? {

'Ubuntu' => 'ssh',

'Redhat' => 'openssh',

default => 'openssh',

},

}

Notes:

operatingsystemisastandardfact.Itisoftenusedtomakecrossplatformportabilitydecisions.

Thematchingalgorithminselectorscanalsoacceptaregularexpressioninsteadofasimplestringbyusing/charactersasdelimiters.

StringmatchinginPuppetiscaseinsensitive.Thismeansthatthereisnodifferencebetween'Ubuntu'and'ubuntu'.Acasesensitivematchcanbeachievedusingaregularexpression./Ubuntu/and/ubuntu/arenotequal.

Puppetrequiresthatallselectorsreturnavalue;soifnobranchesmatch,compilationwillfail.Toavoidthatfailure,youshouldincludeadefaultmatchifasuitabledefaultexists.Ifnot,bestpracticesaretoallowcompilationfailuresoyoudon'tenforceanunexpectedcatalog.

SelectorValues

Fundamentalsv3.4.9 210 ©2015PuppetLabs

Page 211: Fundamentals Puppet

SelectorValues

Thevaluereturnedbyaselectorcanbeassignedtoavariable:

out-statement

$sshpkgname = $::operatingsystem ? {

'ubuntu' => 'ssh',

default => 'openssh',

}

package { 'ssh':

ensure => present,

name => $sshpkgname,

}

SelectorValues

Fundamentalsv3.4.9 211 ©2015PuppetLabs

Page 212: Fundamentals Puppet

CaseStatements

Thecasestatementschooseabranchofcode

Canbeusedaroundresourcesorotherlogicalconstructs:

case $::operatingsystem {

'redhat', 'centos': { include redhat } # apply the RedHat class

'debian', 'ubuntu': { include debian } # apply the Debian class

'windows' : { include windows } # apply the Windows class

'amazon': {

include amazon # include our EC2 config

include redhat # as well as the base RedHat class

}

default: { fail("Unsupported OS: ${::operatingsystem}") }

}

Notes:

Puppetdoesnotrequirethatacasestatementmatchanycases,andassuch,atypocangetyouintounpredictablestatesifyoudon'tcatchthedefaultcase.Bestpracticesaretoalwaysincludeadefaultcaseforcasestatements.Inthatdefaultcase,youshouldexplicitlycallthefailfunctionratherthanenforceanunpredictableconfiguration.

CaseStatements

Fundamentalsv3.4.9 212 ©2015PuppetLabs

Page 213: Fundamentals Puppet

SettingVariables

Casestatementscanbeusedtosetvariablesaswell.

case $::operatingsystem {

'ubuntu': {

$x11_pkg = 'xorg'

$ssh_pkg = 'ssh'

}

'solaris': {

$x11_pkg = 'x11/server/xorg'

$ssh_pkg = 'network/ssh'

}

'windows': {

$x11_pkg = 'xming'

$ssh_pkg = 'putty'

}

# default assumes CentOS, RedHat

default: {

$x11_pkg = 'xorg-x11-server-Xorg'

$ssh_pkg = ['openssh', 'openssh-clients', 'openssh-server']

}

}

package { $x11_pkg:

ensure => present,

}

package { $ssh_pkg:

ensure => present,

}

Notes:

casestatementsareoftenusedwhenyouhavemanyvariablestoset,oryouwishtoconditionallyincludearesourceorresources.

SettingVariables

Fundamentalsv3.4.9 213 ©2015PuppetLabs

Page 214: Fundamentals Puppet

if/elsif/else

Theseconditionalsactonbooleanexpressions.Thefollowingvaluesalwaysevaluateasfalse:

undef(oranundefinedvariable)''

false

Note:Theemptystring('')willevaluatetotrueinfuturereleasesofPuppet.

if $mailserver {

file { '/etc/mail': ensure => directory }

} else {

file { '/etc/mail': ensure => absent }

}

Notes:

Theunlesskeywordworksjustlikeanegatedifstatement.Theexamplegivenabovecouldhavebeeninvertedlikeso:

unless $mailserver {

file { '/etc/mail': ensure => absent }

} else {

file { '/etc/mail': ensure => directory }

}

Somepeoplestronglyobjecttotheuseofunless,feelingthatanegatedifstatementismoreclear.

if/elsif/else

Fundamentalsv3.4.9 214 ©2015PuppetLabs

Page 215: Fundamentals Puppet

if/elsif/else

Morecomplicatedbooleanexpressions.

Chainingexpressions:

if $server != 'mail' and $role != 'mailserver' {

file { '/etc/mail': ensure => absent }

} else {

file { '/etc/mail': ensure => directory }

}

Regularexpressions:

# A production database in North America

$server='prodDBna42'

if $server =~ /DBna\d+$/ {

notify { 'matches regular expression': }

} else {

notify { 'does not match regular expression': }

}

Notes:

StringcomparisonsinPuppetarecaseinsensitive.Togetacasesensitivematch,usearegexwiththe=~operator.

if/elsif/else

Fundamentalsv3.4.9 215 ©2015PuppetLabs

Page 216: Fundamentals Puppet

ConditionalExpressions

Puppetexpressionscanbecomposedof:booleanexpressions

and,or,andnot

comparisonexpressions

==,!=,=~,<,>,<=,>=

arithmeticexpressions

+,-,/,*,<<,>>

membership

in

Notes:

NotethatinPuppet,allstringcomparisonsexceptforwiththeinexpressionarecaseinsensitive.

ConditionalExpressions

Fundamentalsv3.4.9 216 ©2015PuppetLabs

Page 217: Fundamentals Puppet

OperatorPrecedence!(not)* /(timesanddivide)- +(minus,plus)<< >>(leftshiftandrightshift)== != =~(equal,notequal,regexequal)>= <= > < (greater/equal,less/equal,greaterthan,lessthan)and

or

Parenthesescanbeusedtogroupexpressionsandexplicitlysetprecedence.

OperatorPrecedence

Fundamentalsv3.4.9 217 ©2015PuppetLabs

Page 218: Fundamentals Puppet

Functions

ExecutedonthePuppetMaster

Notes:

Functionsrunonlyduringcatalogcompilation.TheycannotbeusedtomakeconditionaldecisionsduringcatalogenforcementontheAgent.

Remember:weusePuppettodefineastatemodelandthentoenforcethatstatemodel.Thismeansthatthemasteralwayshasanaccuratedefinitionofwhatconfigurationeachnodeshouldhave.Ifthecatalogbehavedlikeascriptandwereabletomakeconditionaldecisions,thenthataccuratevisibilityintostatewouldbelostandtherewouldbenocompleterecordofanode'sconfigurationforduplicationordisasterrecovery.

ForacompletelistofavailablefunctionspleasevisitPuppetDocs:http://docs.puppetlabs.com/references/stable/function.html.

Functions

Fundamentalsv3.4.9 218 ©2015PuppetLabs

Page 219: Fundamentals Puppet

Statements

Takeactionswithoutreturningavalue.

Example:

node default {

notice("${::clientcert} has no node definition")

}

Statementfunctionsinclude:

tag:setsatagforallresourcescontainedinthecurrentscopeinclude:evaluateaclassrealize:makesavirtualresourcerealrequire:evaluateoneormoreclasses,addingtherequiredclassasadependencyfail:failwithaparseerror

Statements

Fundamentalsv3.4.9 219 ©2015PuppetLabs

Page 220: Fundamentals Puppet

rvalueFunctions

Returnavaluetobeusedasneeded.

Example:

file { '/etc/httpd/conf.d/my_host.conf':

ensure => file,

content => template('apache/vhost.erb'),

}

rvaluefunctionsinclude:

defined:returnstrueifaclassorresourceisdeclaredfile:returnsthecontentsofafilefromtheservergenerate:returnstheresultsofashellcommandregsubst:regexstringreplacementsha1:returnsaSHA1hashvaluefromastring

rvalueFunctions

Fundamentalsv3.4.9 220 ©2015PuppetLabs

Page 221: Fundamentals Puppet

Lab10.2:PlatformAbstraction

Objective:

Useconditionallogictosupportmultipleoperatingsystems.Ensureyourmodulestillworksonyourownplatform.

Iftimeallows:

Instructormayteststudentcodeonotherplatform(s).

Lab10.2:PlatformAbstraction

Fundamentalsv3.4.9 221 ©2015PuppetLabs

Page 222: Fundamentals Puppet

Checkpoint:LanguageConstructs

HowdoesPuppethandledependenciesbetweenresources?

Resourcedefaultscanoverrideresourceattributes.TrueFalse

if$a='one'and$ab='two',thenwhatwill"$abc"contain?'onebc''twoc'Ifyoudon'twritecodethisway,youwon'tneedtocare

Becausevariablesareimmutable,youcannotdeclarealocalvariablenamed$osfamily.TrueFalse

Someofthemajordifferencesbetweenacasestatementandaselectorinclude:YoucannotsetvariablesincasestatementSelectorsreturnavaluewhilecasestatementschooseacodebranchOnlyselectorshavedefaultmatchersSelectorsarerequiredtomatchanoption,butcasestatementsarenot

Checkpoint:LanguageConstructs

Fundamentalsv3.4.9 222 ©2015PuppetLabs

Page 223: Fundamentals Puppet

ERBTemplates

ERBTemplates

Fundamentalsv3.4.9 223 ©2015PuppetLabs

Page 224: Fundamentals Puppet

Lesson11:ERBTemplates

Objectives

Attheendofthislesson,youwillbeableto:

Describethebenefitsofseparatinglogicfrompresentation.UsePuppettodynamicallygeneratecustomizedconfigurationfilesfortheAgentsystem.ExtendthefunctionalityofyourNginxmoduleusingERBtemplates.

Lesson11:ERBTemplates

Fundamentalsv3.4.9 224 ©2015PuppetLabs

Page 225: Fundamentals Puppet

SeparationofConcerns

Focusononethingatatime.Whenyou'rewritingcode,writecode.Whenyou'redesigningthepresentationofafile,designthatfile.

Benefitsofthislayering:

Constructfilecontentsdynamicallywithoutcomplexcode.Updatefilelayoutwithoutrequiringcodechanges.Reusablefilegenerationpatterns.Allowlesstechnicalpeopletoupdatefilepresentation.Cleaner,morereadablecode.

Don'tclutteryourcleanPuppetcodewithmessystringprocessing.

SeparationofConcerns

Fundamentalsv3.4.9 225 ©2015PuppetLabs

Page 226: Fundamentals Puppet

ERBTemplates

Ruby'sbuilt-intemplatinglanguage.Templatesaremostlyplaintextfiles.InsertingERBtagsallowsyouto:

Displayoractonthecontentsofvariables.Altertheflowoflogic.IncludeRubycodetoperformcalculationsoriterate.

ERBTemplates

Fundamentalsv3.4.9 226 ©2015PuppetLabs

Page 227: Fundamentals Puppet

BasicERBSyntax

Variables

IncludethevalueofaRubyexpressionwiththe"="modifier:

The variable is set to <%= @somevariable %>.

PuppetvariablesCanuseanyvariablesthatcanberesolvedinthecallingmanifest.ThisincludesfactervariablesthatareautomaticallysetbyPuppet.

Usingthe$::ipaddressfactinatemplate:

The IP address of this node is <%= @ipaddress %>.

Notes:

Toaccessvariablesfromotherscopes,simplyassignalocalvariableinyourmanifesttopullitintoscope.Thenaccessitlikeanyother.Forexample:

manifests/init.pp

class myapp {

include myapp::params

$localsetting = $myapp::params::setting

file { '/tmp/out.txt':

ensure => file,

content => template('myapp/file.erb'),

}

}

templates/file.erb

Value from the params class: <%= @localsetting %>.

BasicERBSyntax

Fundamentalsv3.4.9 227 ©2015PuppetLabs

Page 228: Fundamentals Puppet

BasicERBSyntax

Iteration

Wecaniterateoverarraysusingtheruby.eachoperator.

Assumethatthe$puppet_arrayvariablehasbeeninitializedasanarraybythecallingmanifest.

<% @puppet_array.each do |val| -%>

puppet_array has an item with a value of <%= val %>

<% end -%>

Thetrailinghyphenmodifierwillconsumeanewlineimmediatelyfollowingthetag.Itwillpreventextrablanklinesfromappearingintheoutput.

BasicERBSyntax

Fundamentalsv3.4.9 228 ©2015PuppetLabs

Page 229: Fundamentals Puppet

BasicERBSyntax

Conditionals

Wecanuserubystandardconditionalexpressions.

<% if @kernel != 'Linux' %>This is a <%= @kernel %> system.<% end %>

Youcantesttoseeifavariableexists.

<% if @vlan then -%>

The following virtual LANs are configured: <%= @vlan %>

<% end -%>

BasicERBSyntax

Fundamentalsv3.4.9 229 ©2015PuppetLabs

Page 230: Fundamentals Puppet

TemplateFunctionERBtemplatesarereadintoamanifestviathetemplatefunction:

file { '/etc/motd':

ensure => file,

content => template('motd/warning.erb'),

}

Theoutputofthetemplatefunctionisastring,andisassignedasthevalueofthecontentattributeofthefiletype.Itcanalsobeassignedtoavariable:

$warning = template('motd/warning.erb')

Notes:

Forexample,youcanhaveoneconfigfileonthePuppetMasterwhichcustomizesitselfforeachnodebasedonFacterFacts.

Insteadofusingtherelativemodulepathpuppet:///modules/motd/warning.erbitisalsopossibletospecifylocationsusingtheirabsolutepathsuchas/etc/puppetlabs/puppet/templates/warning.erb.Thismaybeusefulwhenreferringtosensitivefilesstoredoutsideofversioncontrol,suchascertificates.

TemplateFunction

Fundamentalsv3.4.9 230 ©2015PuppetLabs

Page 231: Fundamentals Puppet

ConcatenationThetemplatefunctionwillconcatenatemultipletemplates.Theoutputwillincludecontentfromalllistedtemplates.

file { '/etc/motd':

ensure => file,

content => template('motd/header.erb',

'motd/warning.erb'),

}

Concatenation

Fundamentalsv3.4.9 231 ©2015PuppetLabs

Page 232: Fundamentals Puppet

Example

ssh_configtemplateLet'sassumethatourinfrastructureusesCentOSforworkstationsandDebianforservers.WewanttoenableX11forwardingonlyonworkstationclassmachines,notservers.

# Puppet managed ssh_config file

Host *

GSSAPIAuthentication yes

<% if @operatingsystem == 'CentOS' then -%>

ForwardX11 yes

ForwardX11Trusted yes

# virtually no clients support untrusted mode

<% else -%>

ForwardX11 no

<% end -%>

SendEnv LANG LC_*

Notes:

Refertothetemplatingguideathttp://docs.puppetlabs.com/guides/templating.htmlformoreinformation.

Example

Fundamentalsv3.4.9 232 ©2015PuppetLabs

Page 233: Fundamentals Puppet

ModuleOrganization

Templatesarestoredinyourmodulemuchlikefiles.

file { '/var/www/html/index.html':

ensure => file,

content => template('apache/index.html.erb'),

}

[root@training ~]# tree /etc/puppetlabs/puppet/environments/production/modules/apache/

├── manifests│ ├── init.pp ## class apache { ... }├── templates│ └── index.html.erb ## content => template('apache/index.html.erb'),└── examples └── init.pp ## include apache

ModuleOrganization

Fundamentalsv3.4.9 233 ©2015PuppetLabs

Page 234: Fundamentals Puppet

Lab11.1:DynamicContent

Objective:

Useatemplatetodynamicallygenerateawebpagewithinformationcustomizedforthenodeit'sbuiltfor.Replaceplatformspecificstaticconfigurationfileswithtemplatestoaccountforvariation.

Lab11.1:DynamicContent

Fundamentalsv3.4.9 234 ©2015PuppetLabs

Page 235: Fundamentals Puppet

Checkpoint:ERBTemplates

HowdoesPuppetusetemplatestomanagefilecontent?

TemplatesareagoodwaytorunarbitraryRubycode.TrueFalse

Templatesrequireyoutopassinahashofallvariablesyou'lluse.TrueFalse

Templatesreturnahashofvariableswhichcanbeusedinyourmanifest.TrueFalse

Pleasecheckallthestatementsthataretrue:TemplatescanuseallvariablesinscopeTemplatesareconstructedontheagentduringcatalogapplicationTemplatescaniterateoverarraystobuildrepeatingfilestanzasTemplatesshouldbeusedtocalculatedataandpresentit

Checkpoint:ERBTemplates

Fundamentalsv3.4.9 235 ©2015PuppetLabs

Page 236: Fundamentals Puppet

DefinedResourceTypes

DefinedResourceTypes

Fundamentalsv3.4.9 236 ©2015PuppetLabs

Page 237: Fundamentals Puppet

Lesson12:DefinedResourceTypes

Objectives

Attheendofthislesson,youwillbeableto:

Explaintheconceptofdefinedresourcetypes.Constructandusedefinedresourcetypes.Explainhowtoavoidduplicateresourcedefinitionswhendeclaringdefinedresourcetypes.

Lesson12:DefinedResourceTypes

Fundamentalsv3.4.9 237 ©2015PuppetLabs

Page 238: Fundamentals Puppet

DefinedResourceTypesModelrepeatablechunksofconfigurationto:

savetimeandlinesofcode.abstractcomplexity.reduceerrorsandinconsistency.

apache::vhost { 'elmo.puppetlabs.com':

port => '80',

docroot => '/var/www/muppets/elmo',

options => 'Indexes MultiViews',

notify => Service['httpd'],

}

Notes:

DefinedResourceTypesautomaticallyacceptanymetaparameter(likenotify).Moreinformationaboutdefinedresourcescanbefoundathttp://docs.puppetlabs.com/guides/language_guide.html.

DefinedResourceTypes

Fundamentalsv3.4.9 238 ©2015PuppetLabs

Page 239: Fundamentals Puppet

BuildingtheVhostLocation:modulepath/apache/manifests/vhost.pp

define apache::vhost (

$docroot,

$port = '80',

$priority = '10',

$options = 'Indexes MultiViews',

$vhost_name = $title,

$servername = $title,

$logdir = '/var/log/httpd',

) {

file { "/etc/httpd/conf.d/${title}.conf":

ensure => file,

owner => 'apache',

group => 'apache',

mode => '0644',

content => template('apache/vhost.conf.erb'),

}

}

$title = elmo.puppetlabs.com

Thenamegivenwhendeclaringthisapache::vhostresource.AmagicvariablesetbyPuppet.

BuildingtheVhost

Fundamentalsv3.4.9 239 ©2015PuppetLabs

Page 240: Fundamentals Puppet

Resourcetitlesmustbeunique

Evenwhencontainedwithinadefinedtype!Allresourcesinthecatalogmustmaintainuniqueness.Onlyvariableweknowtobeuniqueisthe$titlevariable.

define apache::vhost (

...

) {

file { "/etc/httpd/conf.d/${title}.conf":

...

}

}

Alwaysderivethetitlesofresourcesinadefinedresourcetypefrom$title

Notes:

Ifyouuseastatictitleforresourceinadefinedresourcetype,youwillgetacompilationerrorwhenyouinstantiatethesecondresourceofthattypeinyourmanifest.It'seasytoseewhy;you'reaskingPuppettocreatetworesourcesofthesamename!

Resourcetitlesmustbeunique

Fundamentalsv3.4.9 240 ©2015PuppetLabs

Page 241: Fundamentals Puppet

LeveragingaTemplateLocation:modulepath/apache/templates/vhost.conf.erb

NameVirtualHost <%= @vhost_name %>:<%= @port %>

<VirtualHost <%= @vhost_name %>:<%= @port %>>

ServerName <%= @servername %>

DocumentRoot <%= @docroot %>

<Directory <%= @docroot %>>

Options <%= @options %>

AllowOverride None

Order allow,deny

allow from all

</Directory>

ErrorLog <%= @logdir %>/<%= @title %>_error.log

LogLevel warn

CustomLog <%= @logdir %>/<%= @title %>_access.log combined

ServerSignature Off

</VirtualHost>

Notes:

Itisaverycommonpatternforadefinedtypetoacceptparametersandtosimplypassthemthroughasvariablesforatemplate.

LeveragingaTemplate

Fundamentalsv3.4.9 241 ©2015PuppetLabs

Page 242: Fundamentals Puppet

ModuleOrganization

DefinedResourceTypesshouldbeorganizedlikeclasses.

[root@training ~]# tree /etc/puppetlabs/puppet/environments/production/modules/apache/

├── manifests│ ├── init.pp ## class apache { ... }│ └── vhost.pp ## define apache::vhost { ... }├── templates│ └── vhost.conf.erb ## content => template('apache/vhost.conf.erb'),└── examples └── init.pp ## include apache └── vhost.pp ## apache::vhost { 'training.puppetlabs.com': ... }

Testadefinedtypebydeclaringafewexamplesinatestmanifest.

ModuleOrganization

Fundamentalsv3.4.9 242 ©2015PuppetLabs

Page 243: Fundamentals Puppet

ReusableConfiguration

ReliableandRepeatable

apache::vhost { 'elmo.puppetlabs.com':

docroot => '/var/www/muppets/elmo',

options => 'Indexes MultiViews',

}

apache::vhost { 'piggy.puppetlabs.com':

docroot => '/var/www/muppets/piggy',

options => '-MultiViews',

}

[root@training ~]# ls /etc/httpd/conf.d

elmo.puppetlabs.com.conf piggy.puppetlabs.com.conf

[root@training ~]# lynx http://elmo.puppetlabs.com:80

ReusableConfiguration

Fundamentalsv3.4.9 243 ©2015PuppetLabs

Page 244: Fundamentals Puppet

Lab12.1:ManageVirtualHosts

Objective:

Createadefinedtypetomanageacompletevirtualhostasasingleresource.Refactorexistingcodetoreducecodeduplication.

Lab12.1:ManageVirtualHosts

Fundamentalsv3.4.9 244 ©2015PuppetLabs

Page 245: Fundamentals Puppet

Checkpoint:DefinedResourceTypes

HowcanPuppetcodemodelrepeatedchunksofconfiguration?

Definedresourcetypescancontainresourcesofanytype.TrueFalse

Onedrawbacktodefinedresourcetypesisthatyoucannotestablishdependenciesonthem.TrueFalse

AdefinedresourcetypeisRubycodethatisrunontheagentduringenforcement.TrueFalse

Adefinedresourcetyperequiresacustomprovidertorunontheagent.TrueFalse

Adefinedresourcetypecanprovidecontexttothething(s)beingmanaged.TrueFalse

Checkpoint:DefinedResourceTypes

Fundamentalsv3.4.9 245 ©2015PuppetLabs

Page 246: Fundamentals Puppet

AdvancedClasses

AdvancedClasses

Fundamentalsv3.4.9 246 ©2015PuppetLabs

Page 247: Fundamentals Puppet

Lesson13:AdvancedClasses

Objectives

Attheendofthislesson,youwillbeableto:

Recognizeparameterizedclassesanddescribetheirsyntax.Modifyclassconfigurationsusingparameters.Usetheparamspatterntoassigndefaultparams.Explainthebenefitsofasinglesourceoftruth.RetrievedatafromaHieradatasource.ExplainhowHierainteractswithparameterizedclasses.

Lesson13:AdvancedClasses

Fundamentalsv3.4.9 247 ©2015PuppetLabs

Page 248: Fundamentals Puppet

ParameterizedClasses

Customizebehaviorfordifferentconfigurations.

class ssh (

$server = true, # Enable the server

$client = true, # Enable the client

$allow_root = true, # permit root to log in

$untrusted = false, # permit untrusted hosts to log in

$x11_forward = false, # forward X11 protocol; run remote graphical apps

) {

File {

owner => root,

group => root,

mode => '0440',

}

include ssh::hostkeys # set up keys for trusted hosts

if $server {

include ssh::server # manage server

file { '/etc/ssh/sshd_config':

ensure => file,

content => template('ssh/sshd_config.erb'),

}

}

if $client {

include ssh::client # manage client

file { '/etc/ssh/ssh_config':

ensure => file,

content => template('ssh/ssh_config.erb'),

}

}

}

Notes:

Parameterizedclassescanacceptdefaultvalues(likedefinedresourcetypes).Ifeveryparameterhasadefault,thenyoucanusetheincludefunctionlikewehavebeenupuntilthispoint.

ParameterizedClasses

Fundamentalsv3.4.9 248 ©2015PuppetLabs

Page 249: Fundamentals Puppet

DeclaringaClass

Aclassisjustanotherresource!

Theincludefunctionisashortcutthatacceptsalldefaults:

include ssh

Youcandeclareaclassjustlikeanyotherresource:

class { 'ssh': }

Allowsyoutospecifyparametervalues:

class { 'ssh':

allow_root => false, # don't allow root to log in

untrusted => false, # don't allow logins from untrusted hosts

}

Notes:

Theincludefunctionisidempotent,meaningthatitwilldeclaretheclassonlyifit'snotalreadydeclared.Thismeansthatyoucanincludeaclassanytimeyouknowitisneeded.Forexample,ifadefinedtyperequiressetupfromaparentclass,itshouldincludethatclassitself.

Declaringaclasswiththeresourcesyntax,however,isnotidempotent.Justlikeanyotherresource,youcanonlydeclareclassesonce.

Bestpracticesaretousetheincludefunctionwhenyoucan.However,ifyoumustcustomizeparametersthenyoushouldnotuseincludetoincludethatclassanywhereelseinyourcodebase.Todosowouldputyouinanindeterminatestatethat'sdifficulttodebug.

Onesolutiontothisconundrumistowriteawrapperclassthatwilldeclaretheparameterizedclasswiththerequiredparameters,butnotacceptanyparametersofitsown.EvenbetterwouldbetouseAutomaticDataBindings,whichwillbementionedbrieflyattheendofthislesson.

DeclaringaClass

Fundamentalsv3.4.9 249 ©2015PuppetLabs

Page 250: Fundamentals Puppet

ParameterizedClasses

Supportclassestocustomizeparameterizedclasses.

class ssh::workstation {

class { 'ssh':

x11_forward => true,

}

}

class ssh::bastion {

class { 'ssh':

allow_root => false,

untrusted => true,

}

}

node 'jumphost.example.com' {

include ssh::bastion

...

}

node 'web01.example.com' {

include ssh # accept all default parameters to the ssh class

...

}

Notes:

Nodedeclarationsbecomesimplyalistofclassestoinclude.Thesesupportclasseshavebeencalledaspects,behaviours,roles,etc.Thekeyisthattheyseparatetheimplementationofaconfigurationdescriptionfromtheassignmentofthatconfiguration.Inotherwords,youcandescribeanodeasalistofrolesitshouldserve,ratherthanbeingforcedtoprovideallthedetailsforeachbitofconfigurationeachtimeyouconfigureanode.

ParameterizedClasses

Fundamentalsv3.4.9 250 ©2015PuppetLabs

Page 251: Fundamentals Puppet

EditingClassParameters

EditingClassParameters

Fundamentalsv3.4.9 251 ©2015PuppetLabs

Page 252: Fundamentals Puppet

Lab13.1:ParameterizedClasses

Objective:

Addparameterstoyournginxmoduleallowingitsbehaviourtobecustomized.Declaretheclassparametersinseveralways.

Lab13.1:ParameterizedClasses

Fundamentalsv3.4.9 252 ©2015PuppetLabs

Page 253: Fundamentals Puppet

ClassInheritance

Calculatingparametersdistractsfrompurposeofthecode.

class apache (

$docroot = undef,

) {

if $docroot {

$httpd_docroot = $docroot

} else {

$httpd_docroot = $::osfamily ? {

'redhat' => '/var/www/html',

'debian' => '/var/www',

}

}

file { $httpd_docroot:

ensure => directory,

}

file { "${httpd_docroot}/index.html":

ensure => file,

content => template('apache/index.html.erb'),

}

apache::vhost { $::fqdn:

docroot => $httpd_docroot,

}

...

}

Notes:

Thissnippetofcodeisonlycalculatingplatformvarianceforonevariableacrosstwoplatforms.Realworlduseisactuallymuchmessierandmakesthecodeevenhardertoread.Moreofthecodeendsupbeingsimplydeterminingparametervaluesthanintheactualconfigurationitself!

ClassInheritance

Fundamentalsv3.4.9 253 ©2015PuppetLabs

Page 254: Fundamentals Puppet

ClassInheritance

Putparametercalculationsinaseparateclass.

class apache::params {

case $::osfamily {

'RedHat': {

$httpd_user = 'apache'

$httpd_group = 'apache'

$httpd_pkg = 'httpd'

$httpd_svc = 'httpd'

$httpd_conf = 'httpd.conf'

$httpd_confdir = '/etc/httpd/conf'

$httpd_docroot = '/var/www/html'

}

'Debian': {

$httpd_user = 'www-data'

$httpd_group = 'www-data'

$httpd_pkg = 'apache2'

$httpd_svc = 'apache2'

$httpd_conf = 'apache2.conf'

$httpd_confdir = '/etc/apache2'

$httpd_docroot = '/var/www'

}

default: {

fail("Module ${module_name} is not supported on ${::osfamily}")

}

}

}

Notes:

Allthedefaultparametervaluesgointhisclass.Sinceitisonlydeterminingplatformdifferences,thecodecanoftenbemuchsimplerandeasiertoread.

ClassInheritance

Fundamentalsv3.4.9 254 ©2015PuppetLabs

Page 255: Fundamentals Puppet

ClassInheritance

params.pppatternsimplifiesdefaultparameters.

class apache (

$httpd_user = $apache::params::httpd_user,

$httpd_group = $apache::params::httpd_group,

$httpd_pkg = $apache::params::httpd_pkg,

$httpd_svc = $apache::params::httpd_svc,

$httpd_conf = $apache::params::httpd_conf,

$httpd_confdir = $apache::params::httpd_confdir,

$httpd_docroot = $apache::params::httpd_docroot,

) inherits apache::params {

file { $httpd_docroot:

ensure => directory,

}

file { "${httpd_docroot}/index.html":

ensure => file,

content => template('apache/index.html.erb'),

}

apache::vhost { $::fqdn:

docroot => $httpd_docroot,

}

...

}

Notes:

Thispatternallowsyoutodefaulttosanevaluesfortheplatform,anditalsoallowsyoutopassinparameterstooverridethesedefaultswhenneeded.

It'salsoveryclearandreadable,whichisalwaysawin.

ClassInheritance

Fundamentalsv3.4.9 255 ©2015PuppetLabs

Page 256: Fundamentals Puppet

ClassInheritance

InheritanceConsideredHarmful.Singleinheritanceonly.

Canleadtocomplexinheritancetrees.

Childclassesinheritparentscope.

Notobviouswhereavariableisdeclared.

Bestpracticeistoincludeclassesinsteadofinheritingthem;

Onlybestpracticeuseofinheritanceistheparams.pppattern.

Notes:

Ifwedidnotneedtooverrideparametersoftheapacheclass,thenitcouldbewrittenas:

class apache {

file { $apache::params::httpd_docroot:

ensure => directory,

}

file { "${apache::params::httpd_docroot}/index.html":

ensure => file,

content => template('apache/index.html.erb'),

}

apache::vhost { $::fqdn:

docroot => $apache::params::httpd_docroot,

}

...

}

Bestpracticeistoavoidinheritancewherepossible.

ClassInheritance

Fundamentalsv3.4.9 256 ©2015PuppetLabs

Page 257: Fundamentals Puppet

Lab13.2:ParamsClass

Objective:

RefactorthelogicwritteninthePlatformAbstractionlabintotheparamsclass.Determineallplatformappropriatedefaultsintheparamsclass.

Lab13.2:ParamsClass

Fundamentalsv3.4.9 257 ©2015PuppetLabs

Page 258: Fundamentals Puppet

SingleSourceofTruth

Don'trepeatyourself.Keepsite-specificdataoutofyourmanifests.Puppetclassescanrequestwhateverdatatheyneed,whentheyneedit .BenefitsofretrievingconfigurationdatafromHiera:

Easiertoensurethatallnodesaffectedbychangesinconfigurationdataareupdatedinlockstep.InfrastructureconfigurationscanbemanagedwithoutneedingtoeditPuppetcode.Easiertoreuseorsharemodules.

SingleSourceofTruth

Fundamentalsv3.4.9 258 ©2015PuppetLabs

Page 259: Fundamentals Puppet

Hiera

FlexibleDataLookupExternaldatalookuptool.key:valuedatastorage.Setvaluespernodeorforallnodes.

[root@training ~]# cat /etc/puppetlabs/puppet/environments/production/hieradata/defaults.yaml

---

message: "This is a sample variable that came from Hiera"

[root@training ~]# puppet apply -e "notice(hiera('message'))"

Notice: Scope(Class[main]): This is a sample variable that came from Hiera

Notice: Finished catalog run in 0.18 seconds

Notes:

NotethatHieraisrarelyconfiguredontheAgent,consideringthatfunctionsareexecutedontheMaster.ConfiguringitlocallyallowsyoutoexperimentwithHierausageduringthisclassifyouwish.YourlocalHieraconfigurationwillbeavailablewhenrunningpuppet apply,butnotwhenrequestingacatalogfromtheclassroomMasterwithpuppet agent -t .ThiswillutilizetheHieradatafilesexistingontheMaster.

Hiera

Fundamentalsv3.4.9 259 ©2015PuppetLabs

Page 260: Fundamentals Puppet

ConfigurationDataWithoutHiera

class ntp {

if ( $::fqdn == 'host4.example.com' ) {

$ntpserver = '127.0.0.1'

}

elsif ( $::environment == 'development' or $::fqdn == 'test.example.com' ) {

# Don't forget to update this to the new server on 8/17/2007

$ntpserver = '192.168.2.1'

} else {

$ntpserver = 'us.pool.ntp.org'

}

class { 'ntp::client':

server => $ntpserver,

}

}

ConfigurationDataWithoutHiera

Fundamentalsv3.4.9 260 ©2015PuppetLabs

Page 261: Fundamentals Puppet

ConsumingHieraData

Retrieveconfigurationdatainsteadofhardcodingit.

class { 'ntp::client':

server => hiera('ntpserver','us.pool.ntp.org'),

}

Notes:

Thisprovidesacentrallocationwhereallconfigurationdataiskeptseparatefromtheimplementationdetails.Whenupdatesneedtobemade,asinglechangewillpropagateacrossalltheinfrastructurereducingthechanceofindividualnodesbeingmisconfigured.Itmakestheconfigurationspecificsmoreclear,aswellasreducingcut&pasteconfiguration.Itputsallsitespecificdatainasinglelocation,meaningthatdiscoverabilityisgreatlyimproved,andcutsdownonrequiredinstitutionalknowlege.Italsoreducesthechancesofunintendedsideeffects,suchassyntaxerrorsbreakingcatalogcompilationsforotherunrelatednodes.

ConsumingHieraData

Fundamentalsv3.4.9 261 ©2015PuppetLabs

Page 262: Fundamentals Puppet

HieraConfigurationConfiguredvia/etc/puppetlabs/puppet/hiera.yamlFactsandothervariablesinscopeareusedfordataresolution.

[root@training ~]# cat /etc/puppetlabs/puppet/hiera.yaml

---

:backends:

- yaml

:yaml:

:datadir: '/etc/puppetlabs/puppet/environments/production/hieradata'

:hierarchy:

- "%{clientcert}"

- "%{datacenter}"

- defaults

Thishierarchyisresolvedinorder,basedon:

1. $::clientcert

2. $::datacenter

3. defaultstoreturndefaultvalues.

Notes:

Withthisconfiguration,theHieradatafileswillbequeriedinthisorder:

1. /etc/puppetlabs/puppet/environments/production/hieradata/%{clientcert}.yaml

2. /etc/puppetlabs/puppet/environments/production/hieradata/%{datacenter}.yaml

3. /etc/puppetlabs/puppet/environments/production/hieradata/defaults.yaml

WehaveconfiguredHieratolookin/etc/puppetlabs/puppet/environments/production/hieradatafordatafilesin.yamlformat.Hierawillreplacevariablesinthe:hierarchytreetoconstructfilenames.continued...

HieraConfiguration

Fundamentalsv3.4.9 262 ©2015PuppetLabs

Page 263: Fundamentals Puppet

Forexample,ifweusedthisconfigurationtoretrievethevalueofntpserverforanodenamednode1.example.cominthehoustondatacenter,Hierawouldlookforthekeyntpserverinthefilesbelow,intheorderlisted,andwouldreturnthefirstvaluefound.

1. /etc/puppetlabs/puppet/environments/production/hieradata/node1.example.com.yaml

2. /etc/puppetlabs/puppet/environments/production/hieradata/houston.yaml

3. /etc/puppetlabs/puppet/environments/production/hieradata/defaults.yaml

Youcanseethehierarchyexpandedwhenrunningin--debugmode.

[root@node1 ~]# puppet apply -e 'notice(hiera("ntpserver"))' --debug --environment

development

Debug: hiera(): Hiera YAML backend starting

Debug: hiera(): Looking up ntpserver in YAML backend

Debug: hiera(): Looking for data source node1.example.com

Debug: hiera(): Cannot find datafile

/etc/puppetlabs/puppet/environments/production/hieradata/node1.example.com.yaml,

skipping

Debug: hiera(): Looking for data source development

Debug: hiera(): Cannot find datafile

/etc/puppetlabs/puppet/environments/production/hieradata/houston.yaml, skipping

Debug: hiera(): Looking for data source defaults

Debug: hiera(): Found ntpserver in defaults

[... snip ...]

Notice: Scope(Class[main]): ntp.example.com

Notice: Compiled catalog for node1.example.com in environment development in 0.06 seconds

Notice: Finished catalog run in 0.42 seconds

continued...

HieraConfiguration

Fundamentalsv3.4.9 263 ©2015PuppetLabs

Page 264: Fundamentals Puppet

AvailableHierafunctions:

hiera($key)Callouttohieratolookupakeyusingtheconfigureddatasourcehierarchy.Returnsthefirstvaluefound.

hiera_array($key)Traversestheentirehierarchyandconstructsanarrayofallvaluesfound.Elementscanbeanytype.

hiera_hash($key)Traversestheentirehierarchyandnemrgesallvaluesfoundintoasinglehash.Allvaluesfoundmustbehashes.

hiera_include($key)Callhiera_array()on$keyandincludeallvaluesreturned.$keycanrepresentnode,group,role,etc.andshouldresolvetoalistofclassestoinclude.

HieraConfiguration

Fundamentalsv3.4.9 264 ©2015PuppetLabs

Page 265: Fundamentals Puppet

HieraVisualization

SitewideDefaults

$motd 'Welcometoexample.com'

$ntpserver 'us.pool.ntp.org'

$yumrepo 'yum.example.com'

$mysql_rootpw 'p@ssw0rd'

1. node1.example.com.yaml

2. houston.yaml

3. defaults.yaml

Notes:

Thesenextthreeslidesshouldbevisualizedassheetsofpaperlaidatoponeanother.Ortransparencies,ifyou'reoldschoolenoughtorememberthose.

Onthebottomsheethere,wehaveallthedefaultvaluesforoursite.Theywillapplyifnothingelseoverridesthem.

HieraVisualization

Fundamentalsv3.4.9 265 ©2015PuppetLabs

Page 266: Fundamentals Puppet

HieraVisualization

DatacenterOverrides

$motd 'Location:HoustonDatacenter'

$ntpserver 'us.pool.ntp.org'

$yumrepo 'houston.yum.example.com'

$mysql_rootpw 'p@ssw0rd'

1. node1.example.com.yaml

2. houston.yaml3. defaults.yaml

Notes:

Onthesecondsheetareourdatacenteroverrides.Thisisthesecondlevelofthe:hierarchysetting.Youseethatsomevariablesareoverridden,butthatsomeofthedefaultvariables($ntpserverand$mysql_rootpw)showthrough.

When$::datacenterissetto'houston'andwerequestavariable,thesevaluesarereturned.

HieraVisualization

Fundamentalsv3.4.9 266 ©2015PuppetLabs

Page 267: Fundamentals Puppet

HieraVisualization

NodeSpecificOverrides

$motd 'Location:HoustonDatacenter'

$ntpserver 'us.pool.ntp.org'

$yumrepo 'houston.yum.example.com'

$mysql_rootpw 'hunter2'

1. node1.example.com.yaml2. houston.yaml

3. defaults.yaml

Notes:

Finally,ourtoplevelofthe:hierarchyisthenode's$certname.Thisisrepresentedbythetopsheet.Youseethatonlyonevariableisoverriddenatthislevel,andthatonlyonevariableshowsthroughfromthedefaultslayer.

When$::datacenterissetto'houston'and$certnameissettonode1.example.comandwerequestavariable,thesevaluesarereturned.

Thefinalresultisacompositionofallthelayersinthe:hierarchy.Thiscompositionisconstructedeachtimeavariableisrequested,soitwillbedifferentforeachnode.

HieraVisualization

Fundamentalsv3.4.9 267 ©2015PuppetLabs

Page 268: Fundamentals Puppet

AutomaticDataBindings

LooksupparametervaluesfromHiera.

Hierakeysqueriedareclass::param

[root@training ~]# cat /etc/puppetlabs/puppet/environments/production/hieradata/defaults.yaml

---

ntp::time_server: time.puppetlabs.com

class ntp (

$time_server, # automatically uses hiera('ntp::time_server') as default

$crypto = false, # automatically uses hiera('ntp::crypto', false) as default

) {

file { '/etc/ntp.conf'

content => template('ntp/ntp.conf.erb')

}

}

Simplyincludetheclass:

include ntp

Notes:

AutomaticDataBindingsareanewfeatureofPuppet3.x.

TheresolutionorderofclassparameterswithAutomaticDataBindingsis:

1. Passedinparameters

2. ValueslookedupfromHiera

3. Defaultsexpressedintheclasssignature

AutomaticDataBindingsdoesnotreplacethebuiltinhierafunctions,butmerelyaugmentsthem.

YoucanwriteclassesthatutilizeHieralookups,yetarebackwardscompatiblewithPuppet2.x,bydefaultingtoamanualhierafunctioncallusingthesamekeynamingconventions.Forexample:continued...

AutomaticDataBindings

Fundamentalsv3.4.9 268 ©2015PuppetLabs

Page 269: Fundamentals Puppet

[root@training ~]# cat /etc/puppetlabs/puppet/environments/production/hieradata/global.yaml

---

ntp::time_server: time.puppetlabs.com

class ntp (

$time_server = hiera('ntp::time_server'),

$crypto = hiera('ntp::crypto', false),

) {

file { '/etc/ntp.conf'

content => template('ntp/ntp.conf.erb')

}

}

Simplyincludetheclass:

include ntp

Theonlydifferencebetweenthetwostrategiesisanexplicithieracall.Somepeopleprefertobeexplicittocutdownonopaqueblackmagic.

ThoseinterestedinfurtherreadingonHiera,AutomaticDataBindings,andtheparams.pppatternshouldfollowupwithGaryLarizza'sblogpostathttp://garylarizza.com/blog/2013/12/08/when-to-hiera/.

AutomaticDataBindings

Fundamentalsv3.4.9 269 ©2015PuppetLabs

Page 270: Fundamentals Puppet

Lab13.3:ParameterLookup

Objective:

CustomizeclassparametersusingHiera.DefinerulesusingHieratoclassifyyournode.

Lab13.3:ParameterLookup

Fundamentalsv3.4.9 270 ©2015PuppetLabs

Page 271: Fundamentals Puppet

Checkpoint:AdvancedClasses

BeyondthebasicswithPuppetcode.

Topassparameterstoaclass,youmustusetheincludefunction.TrueFalse

Theparamsclassshouldmanageparametersintheserviceconfigurationfile.TrueFalse

Parameterscanbepassedtoaclassby:WritingadefaultnodedeclarationConfiguringclassparametersintheNodeClassifierDeclaringtheclassusingtheresourcesyntaxandpassingparametersDeclaringappropriatelynamedkeysinHieradatasources

Inheritanceisausefulreplacementfortheincludepattern.TrueFalse

Checkpoint:AdvancedClasses

Fundamentalsv3.4.9 271 ©2015PuppetLabs

Page 272: Fundamentals Puppet

PuppetForge

PuppetForge

Fundamentalsv3.4.9 272 ©2015PuppetLabs

Page 273: Fundamentals Puppet

Lesson14:PuppetForge

Objectives

Attheendofthislesson,youwillbeableto:

UsethePuppetModuleTooltolistinstalledmodules.FindandinstallPuppetmodulesfromtheForge.CreateawrappermodulethatmodifiesaForgemodule'sparameters.

Lesson14:PuppetForge

Fundamentalsv3.4.9 273 ©2015PuppetLabs

Page 274: Fundamentals Puppet

PuppetModuleCommunity

PuppetModuleCommunity

Fundamentalsv3.4.9 274 ©2015PuppetLabs

Page 275: Fundamentals Puppet

PuppetModuleTool

CommandlineinterfaceforthePuppetForgeSearchforModules.InstallModules(withdependencies).ListinstalledModules.

PuppetModuleTool

Fundamentalsv3.4.9 275 ©2015PuppetLabs

Page 276: Fundamentals Puppet

PuppetModuleList

CommandlineinterfaceforthePuppetForge[root@training~]#puppetmodulelist--tree/etc/puppetlabs/puppet/environments/production/modules├──puppetlabs-pe_gem(v0.0.1)├─┬puppetlabs-mysql(v0.6.1)│└──puppetlabs-stdlib(v2.3.3)[/opt/puppet/share/puppet/modules]├──bluetooth(v0.0.2)├──motd(v2.2.1)├──sudo(v0.0.1)├──usermanagement(v0.0.1)└──ssh(v0.0.1)/opt/puppet/share/puppet/modules└─┬puppetlabs-pe_mcollective(v0.0.56)├──puppetlabs-stdlib(v2.3.3)└──puppetlabs-pe_accounts(v1.1.0)[root@training~]#

Notes:

Theversioninformationcomesoutofthemodule'smetadatafilesthatarerequiredforpostingmodulestotheForge.Sincewehaven'twrittenourmodulesforsharing,theyhavenometadataandnoversioningordependencyinformation.

Moreinformationonpublishingmodulescanbefoundathttp://docs.puppetlabs.com/puppet/latest/reference/modules_publishing.html.

PuppetModuleList

Fundamentalsv3.4.9 276 ©2015PuppetLabs

Page 277: Fundamentals Puppet

PuppetModuleSearch

CommandlineinterfaceforthePuppetForge[root@training~]puppetmodulesearchmysqlSearchinghttp://forge.puppetlabs.com...NAMEDESCRIPTIONAUTHORKEYWORDSDavidSchmitt-mysqlManagemysqldatabas...@DavidSchmittmysqldatabaseghoneycutt-mysqlManagemysqlclients...@ghoneycuttmysqldatabasedbsqlghoneycutt-mylvmbackupManagemysqlbackups...@ghoneycuttmysqlbackupdbLVMgastownlabs-ec2_mysqlCreatesaRAIDvolum...@gastownlabsmysqlec2awsamazonmstanislav-mysql_yumPuppet2.@mstanislavmysqlrocha-mysql@rochajonhadfield-wordpressPuppetmoduleto...@jonhadfieldubuntumysqlphprgevaert-mysql@rgevaertmysqlperconamaridbrgevaert-mysqlproxyManagemysql-proxy.@rgevaertproxymysqlmysqlproxyrcoleman-mysqlThismoduleisfor...@rcolemanpuppetlabs-mysqlThismodulehasevol...@bartavelleubuntumysqlsql[root@training~]#

PuppetModuleSearch

Fundamentalsv3.4.9 277 ©2015PuppetLabs

Page 278: Fundamentals Puppet

ForgeModules

Manyexposecustomizableparameters.

puppetlabs/mysql:

class { 'mysql::backup':

backupuser => 'myuser',

backuppassword => 'mypassword',

backupdir => '/tmp/backups',

}

CraigWatson1987/vmwaretools:

class { 'vmwaretools':

version => '8.6.5-621624',

working_dir => '/tmp/vmwaretools'

archive_url => 'http://server.local/my/dir',

archive_md5 => '9df56c317ecf466f954d91f6c5ce8a6f',

}

ForgeModules

Fundamentalsv3.4.9 278 ©2015PuppetLabs

Page 279: Fundamentals Puppet

WrapperModules

SitespecificmodulesthatdeclareForgemodules.Customizeupstreammodules.Definespecificrolesforyourenvironment.

class site::snmpserver {

include snmp

class { 'snmp::server':

ro_community => 'notpublic',

ro_network => '10.20.30.40/32',

contact => '[email protected]',

location => 'Phoenix, AZ',

}

snmp::snmpv3_user { 'myuser':

authpass => '1234auth',

privpass => '5678priv',

}

}

Notes:

Rememberthatclassnamesarealsoscoped.Beawarethatnamesofclassesareresolveddynamically.Thismeansthatifyoucreateasupportclasswiththesameasatoplevelclassyouwillhavetoscopethenameinordertoincludeit.

Forexample:

class site::snmp {

include ::snmp

# ...

}

WrapperModules

Fundamentalsv3.4.9 279 ©2015PuppetLabs

Page 280: Fundamentals Puppet

Exercise14.1:InstallaModule

Objective:

DownloadandexploreoneormorePuppetForgemodules:Followdocumentationtotestthemodulesinaction.

Notes:

Usefulpuppet module toolfunctionstorememberpuppet module list -- treepuppet module searchpuppet module install

Exercise14.1:InstallaModule

Fundamentalsv3.4.9 280 ©2015PuppetLabs

Page 281: Fundamentals Puppet

Checkpoint:ThePuppetForge

SharingcodewiththePuppetForgecommunity.

Youwouldusethepuppetmodulesearchcommandtolistallclassesinamodule.TrueFalse

WrappermodulespassparameterstailoringForgemodulestoindividualsiteneeds.TrueFalse

WhyismakinglocalmodificationstoaForgemoduletypicallyabadidea?MaintainingupdatestothemoduleispainfulSharingbugfixeswiththecommunityletseveryonebenefitLocalchangesarebynaturelesstestedPuppetwillrevertyourchangesanywayYourinstructorwillmakeafrownyfaceatyou

Checkpoint:ThePuppetForge

Fundamentalsv3.4.9 281 ©2015PuppetLabs

Page 282: Fundamentals Puppet

IntroductiontoRoles&Profiles

IntroductiontoRoles&Profiles

Fundamentalsv3.4.9 282 ©2015PuppetLabs

Page 283: Fundamentals Puppet

Lesson15:RolesandProfiles

Objectives

Attheendofthislesson,youwillbeableto:

DescribetheRolesandProfilespattern.IdentifyRolesandProfilesabstractionlayers.WritesimpleRoleandProfileclasses.

Lesson15:RolesandProfiles

Fundamentalsv3.4.9 283 ©2015PuppetLabs

Page 284: Fundamentals Puppet

GoodModuleDesign

AppropriateLevelsofAbstractionModulesonlymanagetheirownresources.

phpmyadminonlymanagesphpMyAdmin,notApacheandMySQL.

Classesshouldbedesignedtobereusableandcomposable.

Stackthemtogetherinmultipledifferentcombinations.

Abstractedimplementationdetails:

Configureforspecificenvironmentsinsteadofre-writingeachtime.

Classifynodesbybusinessrole.

Definenodesbywhattheydo,nothowyouconfigurethemtoachievethat.

Notes:

Classesthataredesignedtobereusableandcomposablemeansthatyoucantakeseveralgeneralpurposeclassesandstackthemtogetherintheconfigurationyouwant.Forexample,youcanuseamoduletomanageawebapplicationalongwithpuppetlabs/apacheandpuppetlabs/mysqltocreateacompleteapplicationimplementationforyoursitewithaminimalamountofactualcoding.

Rigorouslykeepingclasseswithinscopealsomeansthatmultipleapplicationsmaybemanagedonasinglehostwithoutconflicts--aslongastheydon'tattempttomanagecommonresources,suchasApacheorMySQL,themselves!

GoodModuleDesign

Fundamentalsv3.4.9 284 ©2015PuppetLabs

Page 285: Fundamentals Puppet

ImplementationStack

Thisiscalledaprofile.Sitespecificcompositionofgeneralpurposeclasses.Defineorretrieveconfigurationdata.Declareapplicationclasseswithparameters.Littletonologicandfewresourcedeclarations.

class profiles::phpmyadmin {

$docroot = hiera('profiles::phpmyadmin::docroot')

$ssl_cert = hiera('external_ssl_certificate')

$ssl_key = hiera('external_ssl_private_key')

include apache

include phpmyadmin

phpmyadmin::server{ 'default': }

phpmyadmin::vhost { 'db.example.org':

vhost_enabled => true,

docroot => $docroot,

ssl => true,

ssl_cert => $ssl_cert,

ssl_key => $ssl_key,

}

}

Notes:

NoticethatvaluesareretrievedfromHiera.The$docrootparameterlookupisnamespaced,butbecausethe$ssl_certand$ssl_keyparameterlookupsarenotnamespacedwithaclassname,youcaninferthatthesevaluesmightbeusedbymultipleclasseswithintheinfrastructure.

DeclaringthevariablesatthetopoftheclassfilemakesitobviousonfirstglancewhatdataisbeingresolvedfromHieraandisrecommendedforclarity.

ImplementationStack

Fundamentalsv3.4.9 285 ©2015PuppetLabs

Page 286: Fundamentals Puppet

BusinessRole

Thisiscalledarole.Setofimplementationstacksthatmakeupalogicalrole.Compositionofoneormoreprofileclasses.Definesasinglecompleteroleanodemayserve.Nologicatall.

class roles::database_control_panel {

include profiles::base

include profiles::external_host

include profiles::phpmyadmin

}

Rolesonlyimplementprofiles.

BusinessRole

Fundamentalsv3.4.9 286 ©2015PuppetLabs

Page 287: Fundamentals Puppet

Classification

Eachnodeisassignedasinglerole.Nodesshouldonlybeassignedonerole.Exposenoimplementationdetailsatall.

node /^app\d{2,4}\.example\.com$/ {

# matches app01.example.com, etc

include roles::application_server

}

node /^webdb\d{2,4}\.example\.com$/ {

# matches webdb01.example.com, etc

include roles::database_control_panel

}

Notes:

Insteadofdefiningtechnologystacksatthenodelevel,youshouldcreaterolesandassignrolestonodesasrequired.Thelackofimplementationdetailsatthenodeandrolelevelmeansthatyouarefreetoredefinethemasneededandeasilyrefactoryourcompleteinfrastructure.

Ifyouneedtoassignmultiplerolestoanode,thatmeansthatyourroledeclarationsarenotcomplete.Createanewrolethatdefinestheappropriateprofilesandincludethatroleinstead.

Classification

Fundamentalsv3.4.9 287 ©2015PuppetLabs

Page 288: Fundamentals Puppet

Classification

Eachnodeorgroupisassignedasinglerole.OnlyuseroleclassesintheNodeClassifier.Graphicallyassignrolesquicklyandeasily.

Classification

Fundamentalsv3.4.9 288 ©2015PuppetLabs

Page 289: Fundamentals Puppet

RolesandProfiles

Completestack

Notes:

Componentsshouldbenamedafterwhattheymanage(apache,ssh,mysql)Profilesshouldbenamedafterthetechnologystacktheyimplement(database,bastion,mailserver)Rolesshouldbenamedbybusinessroles(load_balancer,web_cluster,application,archive)

RolesandProfiles

Fundamentalsv3.4.9 289 ©2015PuppetLabs

Page 290: Fundamentals Puppet

Checkpoint:RolesandProfiles

HowdoRolesandProfilessimplifyinfrastructuremanagement?

Roles&Profilesallowyoutodefinemachinesbybusinessrole.TrueFalse

AcomponentmoduledesignedtomanagetheRoundcubewebmailinterfaceshouldmanagewhichitems?

Asupportedwebserver,suchasApacheorNginxPHPpackagewithalltherequiredextensionsenabledTheRoundcubewebmailclientAsupporteddatabase,MySQLorPostgreSQLSMTPandIMAPserversformailtransport

AprofileclassdesignedtomanagetheRoundcubewebmailstackshouldmanagewhichitems?Asupportedwebserver,suchasApacheorNginxPHPpackagewithalltherequiredextensionsenabledTheRoundcubewebmailclientAsupporteddatabase,MySQLorPostgreSQLSMTPandIMAPserversformailtransport

Checkpoint:RolesandProfiles

Fundamentalsv3.4.9 290 ©2015PuppetLabs

Page 291: Fundamentals Puppet

CapstoneLab

CapstoneLab

Fundamentalsv3.4.9 291 ©2015PuppetLabs

Page 292: Fundamentals Puppet

CapstoneLab:BloggingPlatform

Objective:

Divideupintoteamsof2-5people.Createaprofileclasstomanageabloggingplatform:

LinuxserversshouldrunWordPressonApache.WindowsserversshouldrunOrchardCMSonIIS.

Hints:

Askyourinstructorforguidanceorsuggestions.UseForgemodulesinsteadofreinventingthewheel.

Notes:

Youshouldworkwithyourteamtocreateaprofileclass,eitherprofile::wordpressorprofile::orchardcms,tomanageablogserveronyourplatformofchoice.Thisprofileshouldstandupawebserver,eitherApacheorIIS,andinstallthebloggingplatformintothedocumentroot.

Instructions:

Thislabpullsfromalllessonslearnedthroughoutthecourse.Workinateamof2-5,asdiscussedwithyourinstructor.Nosinglesolutionorindividualstepsareprovided;youareencouragedtousethecourseliterature,yourownexperience,yourteam'sexperience,andthePuppetdocumentationtosolvethiscapstone.Requestassistancefromtheinstructorasneeded.Youarenotrequiredtousethelistedmodules.Theyaremerelyasuggestion.Workwithinyourgrouptofindthebestsolution.Extracredit:Usethepuppetlabs/firewallmoduletoblockeveryportyoudon'tneed.

continued...

CapstoneLab:BloggingPlatform

Fundamentalsv3.4.9 292 ©2015PuppetLabs

Page 293: Fundamentals Puppet

Hints:

Linux:

Youmayencounterarecentbugwiththepuppetlabs/concatmodulethatpreventsthehunner/wordpressmodulefrommanagingtheWordPresswp_ownerandwp_group.Simplyomitthoseattributestoavoidtheissue.SuggestedForgeModules:

hunner/wordpresscanmanageWordPress.puppetlabs/mysqlcanmanageMySQL.puppetlabs/apachecanmanageApache.

Windows:

ItwilllikelybeeasiertorunyourOrchardCMSblogonport8080insteadofthedefaultsothatitdoesn'tcollidewiththedefaultsite.ChocolateyhasapackageforOrchardCMS.SuggestedForgeModules:

opentable/windowsfeaturecanmanageWindowsfeatures.puppetlabs/dismcanalsomanageWindowsfeatures.opentable/iiscanmanageIISandsites.

NotethatIISinstallationscantakesolongthatthefirstPuppetrunmighttimeout.Theinstallationshouldcomplete,andthesecondPuppetrunwillsucceed.

CapstoneLab:BloggingPlatform

Fundamentalsv3.4.9 293 ©2015PuppetLabs

Page 294: Fundamentals Puppet

CourseConclusion

CourseConclusion

Fundamentalsv3.4.9 294 ©2015PuppetLabs

Page 295: Fundamentals Puppet

CourseSummaryDuringthisclass,we:

UsedPuppetEnterpriseinamaster/agentenvironment.PracticedabasicworkflowfordevelopingPuppetcode.Progressivelydevelopedanddeployedannginxmoduleto:

Managetheinstallationandconfigurationoftheservice.Programmaticallybuildwebpagesusingtemplates.ExtendedthePuppetlanguagetomanagevirtualhostsasresources.

Exploredconditionals,parameterizedclasses,andtheparamspattern.LearnedthebasicsofdataseparationwithHieraandautomaticdatabindings.DesignedprofileclassesusingPuppetForgemodules.

CourseSummary

Fundamentalsv3.4.9 295 ©2015PuppetLabs

Page 296: Fundamentals Puppet

Resources&NextStepsSelfPacedLearning:

DownloadtheLearningVM-http://puppetlabs.com/download-learning-vmPuppetLabsWorkshop-https://puppetlabs.com/learnGetPuppetCertified-http://puppetlabs.com/certificationGetQuestionsAnswered-http://ask.puppetlabs.com

WorkingWithPuppet:

DownloadPuppetEnterprise-manage10nodesforfree

http://puppetlabs.com/download-puppet-enterprise

PuppetDocs-http://docs.puppetlabs.com/IRCCommunityChannel-#puppetonFreenode

Notes:

Needmoretechnicaldetailorproductdrilldown?Scheduleafollow-upcallwithaPuppetLabsProfessionalServicesEngineer.

Getcertifiedwitha25%offvoucher

VoucherCode:PU251411782BValidforthePuppetProfessionalexamataPearsonVUETestingCenternearyouRegisterfortheexamathttp://puppetlabs.com/certification

Asalways,don'tforgettolookforacommunitymoduleontheForgebeforeattackingtheproblemyourself.

Resources&NextSteps

Fundamentalsv3.4.9 296 ©2015PuppetLabs

Page 297: Fundamentals Puppet

TrainingCourses

TrainingCourses

Fundamentalsv3.4.9 297 ©2015PuppetLabs

Page 298: Fundamentals Puppet

UpcomingCoursePreviews

SamplecoveredtopicsPuppetPractitioner PuppetArchitect

Customfactsandfunctions.Manipulatingsectionsoffiles.DesigningmodulesandsharingthemontheForge.TestingPuppetcode.Troubleshootingtechniques.Usingandwritingreportprocessors.

Developmentworkflows.Classificationtechniques.DesigningHierarchies.ManagingPuppetEnvironments.Crossnodeinformationsharing.ScalingPuppet.OrchestrationActions.

Registerforclassesathttp://puppetlabs.com/category/events/upcoming/

UpcomingCoursePreviews

Fundamentalsv3.4.9 298 ©2015PuppetLabs

Page 299: Fundamentals Puppet

HelpShapePuppet

HelpShapePuppet

Fundamentalsv3.4.9 299 ©2015PuppetLabs

Page 300: Fundamentals Puppet

Appendix:References

Appendix:References

Fundamentalsv3.4.9 300 ©2015PuppetLabs

Page 301: Fundamentals Puppet

Glossary

module:Self-containedbundlesofcodeanddata.

idempotent:Abletobeappliedmultipletimeswiththesameoutcome.

define:Tospecifythecontentsandbehaviorofaclassoradefinedresourcetype.Definingaclassortypedoesn'tautomaticallyincludeitinaconfiguration;itsimplymakesitavailabletobedeclared.

declare:TodirectPuppettoincludeagivenclassorresourceinagivenconfiguration.Todeclareresources,usethelowercasefile{"/tmp/bar":}syntax.Todeclareclasses,usetheincludekeywordortheclass{"foo":}syntax.(NotethatPuppetwillautomaticallydeclareanyclassesitreceivesfromanexternalnodeclassifier.)Youcanconfigurearesourceorclasswhenyoudeclareitbyincludingattribute/valuepairs.

Facter:Puppet'ssysteminventorytool.Facterreadsfactsaboutanode(suchasitshostname,IPaddress,operatingsystem,etc.)andmakesthemavailabletoPuppet.Facterincludesalargenumberofbuilt-infacts;youcanviewtheirnamesandvaluesforthelocalsystembyrunningfacteratthecommandline.ThePuppetagentstartstherunbysendingfactstothemaster.

Hiera:Puppet'sdataabstractionlayer.HieraservesasasinglesourceofinformationforacompletePuppetinfrastructureandbecomesthesingleplacewhereallconfigurationdataisstored.

Glossary

Fundamentalsv3.4.9 301 ©2015PuppetLabs

Page 302: Fundamentals Puppet

BestPracticeResourcesPuppetLabsStyleGuide

Fullofusefulconceptstokeepyourcodeintelligiblehttp://docs.puppetlabs.com/guides/style_guide.html

PuppetLabsDocumentation

CredibleinformationoneverythingPuppethttp://docs.puppetlabs.com/

RodJek'spuppet-lint

CheckthatyourPuppetmanifestconformtothestyleguidehttp://puppet-lint.com

puppetparservalidate&automatedtests

Syntaxchecking&verifyingpuppetcodehttp://puppetlabs.com/blog/verifying-puppet-checking-syntax-and-writing-automated-tests/

BestPracticeResources

Fundamentalsv3.4.9 302 ©2015PuppetLabs

Page 303: Fundamentals Puppet

SimplifiedAgentInstall

AutomatepackagebasedAgentinstallationsPuppetEnterpriseprovidespackagerepositoriesforcommonplatformsBydefault,theMasterservesarepositorymatchingitsownplatformAddmoremanagedrepositoriesbyclassifyingtheMaster

Thepe_repo::package::*classeswillbuildandmanagerepositoriesfor:

el_{5,6}_{i386,x86_64}

debian_{6,7}_{i386,amd64}

ubuntu_{10.04,12.04}_{i386,amd64}

sles_11_{i386,x86_64}

Forexample,tosupporttheplatformofCentOS6i386,theMastershouldbeclassifiedwithpe_repo::package::el_6_i386

Installation

Toinstalltheagentrunthefollowingcommandonanycomputeronyournetwork:

[root@agent ~]# curl -k https://<master>:8140/packages/current/install.bash | bash

ThiswillinstallandconfigurethecorrectpackagefortheAgent'splatform,orprovidesensibleerrormessageswithusefulinformationoncorrectingtheproblem.TheAgentwillbeconfiguredtorequestconfigurationfromtheMasterservingtheinstallscript.

SimplifiedAgentInstall

Fundamentalsv3.4.9 303 ©2015PuppetLabs

Page 304: Fundamentals Puppet

PuppetStyleGuideBasicgeneralphilosophies:

Readabilitymatters.Inheritanceshouldbeavoided.ModulesmustworkwithanENCandHierawithoutrequiringthem.Classesshouldgenerallynotdeclareotherclasses.

AdheringtothePuppetstyleguide:

Increasescommunicationbetweenteamsandmembers.Makeserrorsmorereadilydiscoverable.Makescomplexcodemoreconsumablebyothers.Makesiteasiertoreacquaintyourselfwithyourowndormantcode.

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

Readabilitymatters:

Ifyouhavetochoosebetweentwoequallyeffectivealternatives,pickthemorereadableone.Thisis,ofcourse,subjective,butifyoucanreadyourowncodethreemonthsfromnow,that'sagreatstart.Ingeneral,inheritanceleadstocodethatishardertoread.MostusecasesforinheritancecanbereplacedbyexposingclassparametersthatcanbeusedtoconfigureresourceattributesorbylookingdataupfromHiera.

PuppetStyleGuide

Fundamentalsv3.4.9 304 ©2015PuppetLabs

Page 305: Fundamentals Puppet

StyleGuideExample

InternalOrganizationofaClass

Classesshouldbeorganizedwithaconsistentstructureandstyle.

Classes:1.shoulddefinetheclassandparameters.2.shouldvalidateanyclassparametersandfailcatalogcompilationifanyparametersareinvalid.

Sample:fail()catalogcompilation

class myservice($ensure='running') {

if $ensure in [ 'running', 'stopped' ] {

$ensure_real = $ensure

} else {

fail('ensure parameter must be running or stopped')

}

}

Notes:

FromthePuppetStyleGuide

Classes:

1. shouldvalidateanyclassparametersandfailcatalogcompilationifanyparametersareinvalid.

2. shoulddefaultanyvalidatedparameterstothemostgeneralcase.

3. maydeclarelocalvariables.

4. maydeclarerelationshipstootherclasses(e.g.Class['apache'] ->Class['local_yum']).

5. maydeclareresourcedefaults.

6. maydeclareresources(resourcesofdefinedandcustomtypesshouldgobeforethoseofcoretypes).

7. maydeclareresourcerelationshipsinsideofconditionals.

StyleGuideExample

Fundamentalsv3.4.9 305 ©2015PuppetLabs

Page 306: Fundamentals Puppet

CommonConfigurationErrorsTheinstallerisfailing:

1. Is the DNS wrong?

2. Are the security settings wrong?

3. Did you try to install the console before the Puppet Master?

4. How do I recover from a failed install?

Agentnodescan’tretrievetheirconfigurations:

1. Is the Puppet Master reachable from the agents?

2. Can the Puppet Master reach the console?

3. Do your agents have signed certificates?

4. Do agents trust the Master’s certificate?

5. Can agents reach the filebucket server?

MoreinformationonthePuppetLabsDocumentationpagesathttp://docs.puppetlabs.com/

CommonConfigurationErrors

Fundamentalsv3.4.9 306 ©2015PuppetLabs

Page 307: Fundamentals Puppet

MaintenanceTasksSymptom

PE’sconsolebecomessluggishorbeginstakinguptoomuchdisk-space.

PotentialSolution

Severalmaintenancetasksthatcanimproveconsoleperformance:1. Restartingbackgroundtasks2. Optimizingthedatabase3. Cleaningoldreports4. Databasebackups&restores

MoreinformationcanbefoundonthePuppetLabsDocumentationpagesathttp://docs.puppetlabs.com/

InstructionsforperformingthesetaskscancurrentlybefoundonthePuppetDocumentationwebsiteinthePuppetEnterprisemanualathttp://docs.puppetlabs.com/pe/latest/maintain_console-db.html.

MaintenanceTasks

Fundamentalsv3.4.9 307 ©2015PuppetLabs

Page 308: Fundamentals Puppet

ConfigurationManagementasLegos

byAdrienThebo1

Configurationmanagementishard.Configuringsystemsproperlyisalotofhardwork,andtryingtomanageservicesandautomatesystemconfigurationisaseriousundertaking.

Evenwhenyou'vemanagedtogetyourinfrastructureorganizedinPuppetmanifestsorChefcookbooks,organizingyourcodecangetugly,fast.Alltoooftenanewtoolhastobemanagedunderashortdeadline,soanysortofcodewrittentomanageitsolvestheimmediateproblemandnomore.Quickfixesandtemporarycodecanbuildup,andbeforeyouknowit,yourconfigurationmanagementbecomesatangledmess.Nobodyintendsfortheirconfigurationmanagementtooltogetoutofhand,butwithoutguidelinesfordevelopment,allittakesisafewinstancesofgit commit-a -m 'Good enough'fortherottosetin.

Organizingconfigurationmanagementcodeisclearlyagoodidea,buthowdoyoudoit?Fornormaldevelopment,therearemanyofdesignpatternsforlayingoutandorganizingprogramsandlibraries.Traditionalsoftwaredevelopmenthashadaround40yearstomature,andconfigmanagementisfairlyyoungbycomparisonandhasn'thadthetimetohaveformalbestpractices.

ThisisaproposalforanorganizationalpatternthatI'mcallingthe"Legopattern."Admittedly,there'snothingrevolutionaryabouttheseideas.Tobehonest,alltheideasespousedinthisarticlearesimplyapplicationsoftheunix

philosophy2.Thispatterncanbeusedtoorganizecodeforanyconfigurationmanagementtool,butforthesakeofbrevity,I'llbeusingPuppettoprovideexamples.

TheBaseBlocks

Fundamentalbehaviorisprovidedbyasetofbasemodules.TheseareakintotherectangularLegoblocks-they'regeneric,they'rereusable,andyoucanswapthemoutforsimilarpieces.Moduleslikethisshouldbefocusedonthree

tenetsoftheUnixphilosophy:theRuleofModularity,theRuleofComposition,andtheRuleofSeparation3.

Whenwritingbasemodules,theyshouldbe,well,modular.Theyshoulddoonethinganddoitwell.Forinstance,amoduleforinstallingawebapplicationshouldnotmanageadatabaseservice,neithershoulditconfigurelogging.whilethesearevalidconcerns,they'renotdirectlyrelated.Managingonlyoneserviceinonemodulemakesthatmodulemorereusableandmoremaintainable.

Baseblockmodulesshouldalsobebuilttobecomposedwithothermodules.Ifamoduleonlyhandlesoneservice,thenitcanalsosafelyinteractwithsimilarmodules.Forinstance,thatwebappmoduleonlyhandlesinstallingandrunningthewebapp,anothermodulecanhandlebackingupfiles,andtheycanbeusedtogethertosolvethewholeofabusinessproblem.Ifpeoplewanttouseyourmoduleandalsobackuprelatedfiles,theywon'tbeforcedtouseyourbackuptool-theycanuseyourmoduletoprovidetheserviceandusetheirmoduletohandlebackups.

Lastly,baseblockmodulesshouldbebuilttohidetheunderlyingimplementation,andprovideafairlycompleteinterfacetotheservicethatthey'remanaging.Moduleslikethisonlyneedtobemanipulatedviaparametersthattheyexpose(muchlikesoftwarelibraries),soyoucanseewhatoptionsyoucantuneandconfigurewithouthavingtohavecompletemasteryoftheservicethatitsmanaging.Theadvantageofthisisthatyouhaveacleanseparationbetweenhowthecoreelementsoftheservicework,andhowyou'reimplementingthem.

Thepuppetlabs/apache4moduleisagoodexampleofthis.Theapachemoduleisdesignedtogiveyouthesetoftoolsyou'llneedtomanagealmostanyapacheconfigurationregardlessoftheunderlyingsystem.Ithidesthesystem-specificconfigurationandpresentsyouwithasimplerinterfacetoconfigurevhosts,apachemodules,andfurthertoensurethatthenecessarypackagesareinstalledandtheserviceisrunning.Whenusingthismoduleyoucouldhaveavhostdefinedlikethis:

apache::vhost { 'www.example.com':

vhost_name => '192.126.100.1',

port => '80',

docroot => '/home/www.example.com/docroot/',

logroot => '/srv/www.example.com/logroot/',

serveradmin => '[email protected]',

serveraliases => ['example.com',],

}

ConfigurationManagementasLegos

Fundamentalsv3.4.9 308 ©2015PuppetLabs

Page 309: Fundamentals Puppet

Theapache::vhostprovidesalltheoptionsthatyoucouldtune,andyousetthemasneeded.Youdon'tneedtohavetotouchtheunderlyingtemplatesused,orknowthesyntaxofapacheconfiguration,orreallyanythingabouthowthemoduleworks,asidefromtheoptionspresentedbythevhost.

Fundamentally,theapachemoduledoesonething,anddoesonethingwell.Itdoesn'thandlethingslikemonitoring,backups,anditdoesn'ttrytorunbackendservices.Youcanusethismoduletorunapache,andcombineitwithothermodulestobuildtherestofyourconfiguration.

TheWeirdBlocksandCodeLayout

Ofcourse,everysitehastheirowninternalservicesandapplications,andthisiswheretheweirdblockscomein.WeirdblocksareanalogoustotheLegoblocksthathaveaxlesorhingesstickingout:they'redesignedtodosomethingveryspecificandcan'treallybereusedanywhereelse.Inturn,nothingelsecanprovidethebehaviorthattheyprovide.

Generally,thesegenerallyshouldbewrittenlikebaseblocksbutwithacoupleoftwists.Onetwististhatsincethesemodulescannotbereusedelsewhere,itcanmakesensetoembedsitespecificdataintemplatesandmanifests.Secondly,thesemodulesarelocatedinadifferentplaceonthefilesystem.UsingthePuppetmodulepathsettingorchefcookbook_pathsetting,youcanspecifyalistoflocationstocheckformodules.Youcantakeadvantageofthistolocatereusablebaseblocksinoneplace,andweirdblocksinanotherplace.

├── base-blocks│ └── apache│ ├── manifests│ │ ├── init.pp│ │ ├── ssl.pp│ │ └── vhost.pp│ └── templates│├── weird-blocks│ └── boardie│ ├── manifests│ │ └── init.pp│ └── templates│ └── config.yml.erb

Differentiatingbetweenbaseblocksandweirdblocksissurprisinglypowerful.Thedistinctionmakespublishingyourbase-blockseasier,andallowsyoutoeasilytellwhatsortofworkamoduleisexpectedtodo.

Thisseparationcanalsobeusedtocontrolaccess-perhapsoneteammanagesaninternalservice,sotheycanhandletheconfigurationmanagementforthatservice.Howeverthisteamwon’tbeadministeringtherestofyourinfrastructure.Givingthemaccesstotheweird-blocksdirectorymeansthey’llbeabletodotheirjob,butthey’llbeboundtorespectingtheinterfacesofthebase-blocksinsteadoftakingshortcutsandputtingsitespecificchangesinyourbaseblocks.

ComposingBlocksintoServices(likeLegokits)

Sowehaveallofthesewelldefinedmodulesandclasses,butwithoutassemblingthemyouhaveapileoflegos-somethingthat'snotusefulandmainlyexiststocausesearingpainwhenyousteponone.Therefore,weneedsomesortofconcept,likeasiteconfiguration,whereyoutaketheseindividualpartsandsnapthemintoconfigurationsthatworkforyou.

Buildingontopofthemultiplemodule-pathideaoutline,assembledmodulesgoinasite-servicesdirectory,likeso:

├── site-services│ └── infrastructure│ └── manifests│ ├── dhcp.pp│ ├── mrepo.pp│ ├── webserver.pp│ └── postgresql.pp

Withinthissite-servicesdirectory,youbuildoutmodulesthatprovideacompletesolution.Forinstance,theinfrastructure::postgresqlmodulewoulddothingslikeusethepostgresqlmoduletoinstallandrunthepostgresservice,usethenagiosmoduleformonitoringpostgresql,usethebackupexecmoduletobackitup,andsoforth.Inaddition,thisiswhereyouinjectthesite-specificconfigurationintothemodules,sothisiswhereyoumaketheunderlyingmodulesworkforyourinfrastructure.

ConfigurationManagementasLegos

Fundamentalsv3.4.9 309 ©2015PuppetLabs

Page 310: Fundamentals Puppet

Thingsinsite-servicesgenerallywon'tdirectlyincluderesourcesandwillonlyincludeotherclasses.Putanotherway,theyexistalmostentirelytoaggregateclassesintousableunitsandconfiguretheirsettings.Thefollowingexample

wouldbeanexampleofeverythingyouwouldneedtobringupthemrepo5infrastructureonanode:

class infrastructure::mrepo {

motd::register {'mrepo': }

class { 'staging':

path => '/opt/staging',

owner => 'root',

group => 'root',

mode => '0755',

}

$mirror_root = '/srv/mrepo'

class { 'mrepo::params':

src_root => $mirror_root,

www_root => "${mirror_root}/www",

user => "root",

group => "root",

}

class { 'mrepo::exports':

clients => '192.168.100.0/23',

}

# Bring in a list of the actual repositories to instantiate

include infrastructure::mrepo::centos

}

Usingthismodelanyonecanusethemrepomodule,andourownimplementationcanbeusedwithincludeinfrastructure::mrepo.Wehaveaclearseparationofthemrepoimplementationandhowwe'reusingit.

Roles:They’reLikeLegoCities

Atthispoint,wehavethemodulesbuiltinsite-servicesthatconfigureourenvironmentthewayweneedit.Thefinalstepistakingtheseservicesandgroupingthemintoconfigurationsthatwe'llapplytomachines.Forinstance,bringingupanewwebservercouldinvolveincludingmodulesfromsite-servicestosetupourconfigurationsSSH,Apache,andPostgres.Bringingupanewhostforbuildingpackageswouldmeanbringinginoursite-specificconfigurationsforTomcat,Jenkins,andcompilersandsuch.Thiswouldgiveusahierarchylikethis:

├── site-roles│ ├── buildhosts│ │ └── manifests│ │ ├── init.pp│ │ ├── jenkins.pp│ │ └── compilers.pp│ ││ └── webservices│ ├── manifests│ │ ├── redmine.pp│ │ └── wordpress.pp

Eachmanifestinherewouldbeafurtherabstractionontopofthesite-servicesmodule.Theywouldlooksomethinglikethis:

class webservices::redmine {

include infrastructure::apache::passenger

include infrastructure::mysql

class { 'custom_redmine':

vhost_name => $fqdn,

serveraliases => "redmine.${domain} redmine-${hostname}.${domain}",

www_root => '/srv/passenger/redmine',

}

pam::allowgroup { 'redmine-devs': }

pam::allowgroup { 'redmine-admins': }

sudo::allowgroup { 'redmine-admins': }

}

Thisfinallayertakesallourimplementationsofapacheandmysqlandappliesthem,controlssystemaccess,andprovidesforacompleteredminestack.Includingthisoneclass,webservicse::redmine,isallittakestoprovideforeveryrequirementofaredmineinstance,sodeployingmoremachinesforaspecificrolemeansincludingasingleself

ConfigurationManagementasLegos

Fundamentalsv3.4.9 310 ©2015PuppetLabs

Page 311: Fundamentals Puppet

(imagecreditbrickfrenzy6)

containedclass.

Thisgivesusthefollowinghierarchy

base-blocksandweird-blocksprovidebasicfunctionalitysite-servicesassembleblocksintofunctionalservicessite-rolesassembleservicesintofullyfunctionalandindependentroles

Ifyouusethispattern,innotime,youcouldhaveconfigurationmanagementcodethatisaboutasawesomeasasevenfootreplicaofSerenity.

ArticleSource:http://sysadvent.blogspot.com/2012/12/day-13-configuration-management-as-legos.html

1.https://twitter.com/nullfinch2.http://en.wikipedia.org/wiki/Unix_philosophy3.http://www.faqs.org/docs/artu/ch01s06.html4.http://forge.puppetlabs.com/puppetlabs/apache5.http://dag.wieers.com/home-made/mrepo/6.http://www.flickr.com/photos/brickfrenzy/

ConfigurationManagementasLegos

Fundamentalsv3.4.9 311 ©2015PuppetLabs

Page 312: Fundamentals Puppet

Appendix:LiveManagement

Appendix:LiveManagement

Fundamentalsv3.4.9 312 ©2015PuppetLabs

Page 313: Fundamentals Puppet

LiveManagementisDeprecatedLiveManagementisdeprecatedinPE3.8.0andwillbereplacedbyimprovedresourcemanagementfunctionalityinfuturereleases.Forthisreason,LiveManagementisnotenabledbydefaultonnewinstallationsasinpreviousversionsofPE.TheMCollectiveorchestrationenginethatpowersLiveManagementisnotdeprecatedandallfunctionalitydescribedinthissectionispossiblefromthecommandline.

EnablingLiveManagementonnewinstallations

ToenableLiveManagementonnewinstallations,youshouldinstallPEwithananswerfile,andsetq_disable_live_managementton.(Notethatthedefaultisy.)EnablingLiveManagementviatheweb-basedinstallerisnotavailable.

Upgradingexistinginstallations

ThestatusofLiveManagementisnotmanagedduringanupgradeofPEunlessyouspecificallyrequestthatinananswerfile.Inotherwords,ifyourexistinginstallationofPEhasLiveManagementenabled,itwillremainenabledafteryouupgradeunlessyouexplicitlyaddq_disable_live_manangement=yinananswerfile.

Enablingordisablingafterinstallation

Youcanenable/disableLiveManagementatanytimebychangingthedisable_live_managementsettingin/etc/puppetlabs/puppet-dashboard/settings.ymlonthenodeservingasthePuppetEnterpriseConsole.

Notethataftermakingyourchange,youmustrunsudo /etc/init.d/pe-httpdrestarttocompletetheprocess.

LiveManagementisDeprecated

Fundamentalsv3.4.9 313 ©2015PuppetLabs

Page 314: Fundamentals Puppet

NetworkVisibility

Gaininstantinsightintothestateoftheinfrastructure.

LiveManagementresourcebrowsinggivesyou:

1. Instantvisibilityintothestateoftheresourcesonallnodes.

2. Abilitytoquicklyfilterandbrowsetofindtheinformationyouneed.

3. Variationreportsthatcanbegeneratedinjustafewclicksofthemouse.

Notes:

Exampleuse-cases:QuicklyinspectyourentireinfrastructuretodeterminevulnerablenodeswhenaCVEisreleased.Effortlesslyproduceapplicationinstallcountsduringlicensecomplianceaudits.

NetworkVisibility

Fundamentalsv3.4.9 314 ©2015PuppetLabs

Page 315: Fundamentals Puppet

InspectResourcesAcrossAllNodes

InspectResourcesAcrossAllNodes

Fundamentalsv3.4.9 315 ©2015PuppetLabs

Page 316: Fundamentals Puppet

ViewVariationAcrossNodes

ViewVariationAcrossNodes

Fundamentalsv3.4.9 316 ©2015PuppetLabs

Page 317: Fundamentals Puppet

Orchestration

"Commandandcontrol"updatestoclustersofnodes.

Notes:

PuppetEnterprise'sorchestrationcapabilityprovides"commandandcontrol"powertoissuecommandstomultiplenodesonyourinfrastructureatonce.Thismaintainsthemodel-basedintegrityandscalabilityofPuppetwhilealsoprovidingmoredirectimmediatecontrolofinfrastructureelementswhenneeded.

Discoversthestateoftheresourcesonallnodes.Allowssysadminstoprogressivelyroll-outupdates.Allowssysadminstoimplementconfigurationupdatesacrossallnodeswithasinglecommand.

Exampleuse-cases:Easilymanagingcomplexapplicationdeploymentsinstages.Quicklyandsimultaneouslypatchingasecurityvulnerabilityonallaffectednodes.

Orchestration

Fundamentalsv3.4.9 317 ©2015PuppetLabs

Page 318: Fundamentals Puppet

IssuePuppetCommands

Notes:

TheRunbuttonunderrunonceisthesameasrunningpuppet agent -t fromthecommandline.

IssuePuppetCommands

Fundamentalsv3.4.9 318 ©2015PuppetLabs

Page 319: Fundamentals Puppet

InspectaPuppetResource

Notes:

ThepuppetraltaskallowsdirectinteractionwiththePuppetResourceAbstractionLayerontheAgent,justlikerunningpuppet resource.

InspectaPuppetResource

Fundamentalsv3.4.9 319 ©2015PuppetLabs

Page 320: Fundamentals Puppet

SystemPackageManagement

Notes:

SeethatwehavefilterednodestomatchonlyRedHatfamilysystems.Thistaskwillonlyrunonmatchingnodes.

SystemPackageManagement

Fundamentalsv3.4.9 320 ©2015PuppetLabs

Page 321: Fundamentals Puppet

ManageSystemServices

Notes:

Herewehavechosentorestartthepostfixserviceontwospecificnodesbyselectingtheminthelefthandlist.

ManageSystemServices

Fundamentalsv3.4.9 321 ©2015PuppetLabs

Page 322: Fundamentals Puppet

Appendix:Resources

Appendix:Resources

Fundamentalsv3.4.9 322 ©2015PuppetLabs

Page 323: Fundamentals Puppet

Appendix:Resources

Fundamentalsv3.4.9 323 ©2015PuppetLabs

Page 324: Fundamentals Puppet

Appendix:Resources

Fundamentalsv3.4.9 324 ©2015PuppetLabs

Page 325: Fundamentals Puppet

Appendix:Resources

Fundamentalsv3.4.9 325 ©2015PuppetLabs

Page 326: Fundamentals Puppet

Appendix:Resources

Fundamentalsv3.4.9 326 ©2015PuppetLabs

Page 327: Fundamentals Puppet

Appendix:Resources

Fundamentalsv3.4.9 327 ©2015PuppetLabs