Use Puppet Modules to Create a LAMP Stack
Traducciones al EspañolEstamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
DeprecatedThis guide has been deprecated and is no longer being maintained. Please refer to the updated version of this guide.



Within Puppet, modules are the building blocks of your servers’ configurations. Modules install and configure packages, create directories, and generate any other server changes that the user includes in the module. A Puppet module aims to perform all parts of a certain task, such as downloading the Apache package, configuring all files, changing the MPM data, and setting up virtual hosts. Modules are, in turn, broken down into classes that are .pp files meant to simplify the module into various tasks and improve the module’s readability for any future users.
In this guide, Apache and PHP modules will be created from scratch, and a MySQL module will be adapted from the Puppet Lab’s MySQL module found on the Puppet Forge. These steps will create a full LAMP stack on your server and provide an overview of the various ways modules can be utilized.
Create the Apache Module
From the Puppet Master, navigate to Puppet’s module directory and create the
apachedirectory:cd /etc/puppet/modules sudo mkdir apacheFrom within the
apachedirectory, createmanifests,templates,files, andexamplesdirectories:cd apache sudo mkdir {manifests,templates,files,examples}Navigate to the
manifestsdirectory:cd manifestsFrom here, the module will be separated into classes, based upon the goals of that particular section of code. In this instance, there will be an
init.ppclass for downloading the Apache package, aparams.ppfile to define any variables and parameters,config.ppto managed any configuration files for the Apache service itself, and avhosts.ppfile to define the virtual hosts. This module will also make use of Hiera data to store variables for each node.
Create the Initial Apache Class and Parameters
From within the
manifestsdirectory, aninit.ppclass needs to be created. This class should share its name with the module name:- File: /etc/puppet/modules/apache/manifests/init.pp
1 2 3class apache { }
This file will be used to install the Apache package. Ubuntu 14.04 and CentOS 7 have different package names for Apache, however. Because of this, a variable will be used:
- File: /etc/puppet/modules/apache/manifests/init.pp
1 2 3 4 5 6 7 8class apache { package { 'apache': name => $apachename, ensure => present, } }
The
packageresource allows for the management of a package. This is used to add, remove, or ensure a package is present. In most cases, the name of the resource ('apache', above) should be the name of the package being managed. Because of the difference in naming conventions, however, this resource is simply calledapache, while the actual name of the package is called upon with thenamereference.name, in this instance, calls for the yet-undefined variable$apachename. Theensurereference ensures that the package ispresent.Now that there are variables that need to be defined, the
params.ppclass will come into play. While these variables could be defined within theinit.ppcode, because more variables will need to be used outside of the resource type itself, using aparams.ppclass allows for variables to be defined inifstatements and used across multiple classes.Create and open
params.pp:- File: /etc/puppet/modules/apache/manifests/params.pp
1 2 3class apache::params { }
Outside of the original
init.ppclass, each class name needs to branch off ofapache. As such, this class is calledapache::params. The name after the double colon should share a name with the file.The parameters should now be defined. To do this, an
ifstatement will be used, pulling from information provided by Facter, which is already installed on the Puppet master. In this case, Facter will be used to pull down the operating system family (osfamily), to discern if it is Red Hat or Debian-based.The skeleton of the
ifstatement should resemble the following:- File: /etc/puppet/modules/apache/manifests/params.pp
1 2 3 4 5 6 7 8 9 10 11class apache::params { if $::osfamily == 'RedHat' { } elseif $::osfamily == 'Debian' { } else { print "This is not a supported distro." } }
And once we’ve added the variables that have already been referenced:
- File: /etc/puppet/modules/apache/manifests/params.pp
1 2 3 4 5 6 7 8 9 10 11class apache::params { if $::osfamily == 'RedHat' { $apachename = 'httpd' } elseif $::osfamily == 'Debian' { $apachename = 'apache2' } else { print "This is not a supported distro." } }
Note For the duration of this guide, when something needs to be added to the parameter list the variables needed for Red Hat and Debian will be provided, but the expanding code will not be shown. A complete copy ofparams.ppcan be viewed here.With the parameters finally defined, we need to call the
params.ppfile and the parameters intoinit.pp. To do this, the parameters need to be added after the class name, but before the opening curly bracket ({):- File: /etc/puppet/modules/apache/manifests/init.pp
1 2 3class apache ( $apachename = $::apache::params::apachename, ) inherits ::apache::params {
The value string
$::apache::params::valuetells Puppet to pull the values from theapachemodules,paramsclass, followed by the parameter name. The fragmentinherits ::apache::paramsallows forinit.ppto inherit these values.
Manage Configuration Files
Apache has two different configuration files, depending on whether you are working on a Red Hat- or Debian-based system. These can be pulled off a server, or viewed here: httpd.conf (Red Hat), apache2.conf (Debian).
Copy the
httpd.confandapache2.conffiles to thefilesdirectory located at/etc/puppet/modules/apache/files/.Both files need to be edited to turn
KeepAlivesettings toOff. This setting will need to be added tohttpd.conf. Otherwise, a comment should to added to the top of each file:- File: /etc/puppet/modules/apache/files/httpd.conf
1# This file is managed by Puppet
These files now need to be added to the
init.ppfile, so Puppet will know where they are located on both the master server and agent nodes. To do this, thefileresource is used:- File: /etc/puppet/modules/apache/manifests/init.pp
1 2 3 4 5file { 'configuration-file': path => $conffile, ensure => file, source => $confsource, }
Because the configuration file is found in two different locations, the resource is given the generic name
configuration-filewith the file path defined as a parameter with thepathattribute.ensureensures that it is a file.sourceis another parameter, which will call to where the master files created above are located on the Puppet master.Open the
params.ppfile. The$conffileand$confsourcevariables need to be defined within theifstatement:- File: /etc/puppet/modules/apache/manifests/params.pp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15if $::osfamily == 'RedHat' { ... $conffile = '/etc/httpd/conf/httpd.conf' $confsource = 'puppet:///modules/apache/httpd.conf' } elsif $::osfamily == 'Debian' { ... $conffile = '/etc/apache2/apache2.conf' $confsource = 'puppet:///modules/apache/apache2.conf' } else { ...
These parameters will also need to be added to the
init.ppfile, following the example of the additional parameters. A complete copy of theinit.ppfile can be seen here.When the configuration file is changed, Apache needs to restart. To automate this, the
serviceresource can be used in combination with thenotifyattribute, which will call the resource to run whenever the configuration file is changed:- File: /etc/puppet/modules/apache/manifests/init.pp
1 2 3 4 5 6 7 8 9 10 11file { 'configuration-file': path => $conffile, ensure => file, source => $confsource, notify => Service['apache-service'], } service { 'apache-service': name => $apachename, hasrestart => true, }
The
serviceresource uses the already-created parameter that defined the Apache name on Red Hat and Debian systems. Thehasrestartattribute will trigger a restart of the defined service.
Create the Virtual Hosts Files
The Virtual Hosts files will be managed differently, depending on whether the server is based on Red Hat or Debian distributions. Because of this, the code for virtual hosts will be encased in an if statement, similar to the one used in the params.pp class but containing actual Puppet resources. This will provide an example of an alternate use of if statement within Puppet’s code.
From within the
apache/manifests/directory, create and open avhosts.ppfile.Create the skeleton of the
ifstatement:- File: /etc/puppet/modules/apache/manifests/vhosts.pp
1 2 3 4 5 6 7 8 9 10 11class apache::vhosts { if $::osfamily == 'RedHat' { } elsif $::osfamily == 'Debian' { } else { } }
The location of the virtual hosts file on our CentOS 7 server is
/etc/httpd/conf.d/vhost.conf. This file will need to be created as a template on the Puppet master. The same needs to be done for the Ubuntu virtual hosts file, which is located at/etc/apache2/sites-available/example.com.conf, replacingexample.comwith the server’s FQDN. The template for this file also needs to be created on the Puppet master. Navigate to thetemplatesfile within theapachemodule, and then create two files for your virtual hosts:For Red Hat systems:
- File: /etc/puppet/modules/apache/templates/vhosts-rh.conf.erb
1 2 3 4 5 6 7 8<VirtualHost *:80> ServerAdmin <%= @adminemail %> ServerName <%= @servername %> ServerAlias www.<%= @servername %> DocumentRoot /var/www/<%= @servername -%>/public_html/ ErrorLog /var/www/<%- @servername -%>/logs/error.log CustomLog /var/www/<%= @servername -%>/logs/access.log combined </Virtual Host>
For Debian systems:
- File: /etc/puppet/modules/apache/templates/vhosts-deb.conf.erb
1 2 3 4 5 6 7 8 9 10 11<VirtualHost *:80> ServerAdmin <%= @adminemail %> ServerName <%= @servername %> ServerAlias www.<%= @servername %> DocumentRoot /var/www/html/<%= @servername -%>/public_html/ ErrorLog /var/www/html/<%- @servername -%>/logs/error.log CustomLog /var/www/html/<%= @servername -%>/logs/access.log combined <Directory /var/www/html/<%= @servername -%>/public_html> Require all granted </Directory> </Virtual Host>
Only two variables are used in these files:
adminemailandservername. These will be defined on a node-by-node basis, within thesite.ppfile.Return to the
vhosts.ppfile. The templates created can now be referenced in the code:- File: /etc/puppet/modules/apache/manifests/vhosts.pp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17class apache::vhosts { if $::osfamily == 'RedHat' { file { '/etc/httpd/conf.d/vhost.conf': ensure => file, content => template('apache/vhosts-rh.conf.erb'), } } elsif $::osfamily == 'Debian' { file { "/etc/apache2/sites-available/$servername.conf": ensure => file, content => template('apache/vhosts-deb.conf.erb'), } } else { print "This is not a supported distro." } }
Both distribution families call to the
fileresource and take on the title of the virtual host’s location on the respective distribution. For Debian, this once more means referencing the$servernamevalue. Thecontentattribute calls to the respective templates.Note Values containing variables, such as the name of the Debian file resource above, need to be wrapped in double quotes ("). Any variables in single quotes (') are parsed exactly as written and will not pull in a variable.Both virtual hosts files reference two directories that are not on the distributions by default. These can be created through the use of the
fileresource, each located within theifstatement. The completevhosts.conffile should resemble:- File: /etc/puppet/modules/apache/manifests/vhosts.pp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36class apache::vhosts { if $::osfamily == 'RedHat' { file { '/etc/httpd/conf.d/vhost.conf': ensure => file, content => template('apache/vhosts-rh.conf.erb'), } file { "/var/www/$servername": ensure => directory, } file { "/var/www/$servername/public_html": ensure => directory, } file { "/var/www/$servername/log": ensure => directory, } } elsif $::osfamily == 'Debian' { file { "/etc/apache2/sites-available/$servername.conf": ensure => file, content => template('apache/vhosts-deb.conf.erb'), } file { "/var/www/$servername": ensure => directory, } file { "/var/www/html/$servername/public_html": ensure => directory, } file { "/var/www/html/$servername/logs": ensure => directory, } } else { print "This is not a supported distro." } }
Test and Run the Module
From within the
apache/manifests/directory, run thepuppet parseron all files to ensure the Puppet coding is without error:sudo puppet parser validate init.pp params.pp vhosts.ppIt should return empty, barring any issues.
Navigate to the
examplesdirectory within theapachemodule. Create aninit.ppfile and include the created classes. Provide variables forservernameandadminemail:- File: /etc/puppet/modules/apache/examples/init.pp
1 2 3 4 5$serveremail = 'webmaster@example.com' $servername = 'example.com' include apache include apache::vhosts
Test the module by running
puppet applywith the--nooptag:sudo puppet apply --noop init.ppIt should return no errors, and output that it will trigger refreshes from events. To install and configure apache on the Puppet master, this can be run again without
--noop, if so desired.Navigate back to the main Puppet directory and then to the
manifestsfolder (not the one located in the Apache module). If you are continuing this guide from the Puppet Setup guide, you should have asite.ppfile already created. If not, create one now.Open
site.ppand include the Apache module for each agent node. Also input the variables for theadminemailandservernameparameters. If you followed the Puppet Setup guide, a single node configuration withinsite.ppwill resemble the following:- File: /etc/puppet/manifests/site.pp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41node 'ubuntuhost.example.com' { $adminemail = 'webmaster@example.com' $servername = 'hostname.example.com' include accounts include apache include apache::vhosts resources { 'firewall': purge => true, } Firewall { before => Class['firewall::post'], require => Class['firewall::pre'], } class { ['firewall::pre', 'firewall::post']: } } node 'centoshost.example.com' { $adminemail = 'webmaster@example.com' $servername = 'hostname.example.com' include accounts include apache include apache::vhosts resources { 'firewall': purge => true, } Firewall { before => Class['firewall::post'], require => Class['firewall::pre'], } class { ['firewall::pre', 'firewall::post']: } }
To run the new module on your agent nodes, log in to the nodes and run:
sudo puppet agent -t
Using the MySQL Module
Many modules needed to run a server already exist within Puppet Lab’s Puppet Forge. These can be configured just as extensively as a module that you created and can save time since the module need not be created from scratch.
Install the Puppet Forge’s MySQL module by PuppetLabs:
sudo puppet module install puppetlabs-mysql
This will also install any prerequisite modules.
Use Hiera to Create Databases
Before you begin to create the configuration files for the MySQL module, consider that you may not want the same values to be used across all agent nodes. To supply Puppet with the correct data per node, Hiera is used. In this instance, you will be using a different root password per node, thus creating different MySQL databases.
Navigate to
/etc/puppetand create Hiera’s configuration filehiera.yamlin the mainpuppetdirectory:- File: /etc/puppet/hiera.yaml
1 2 3 4 5 6 7:backends: - yaml :yaml: :datadir: /etc/puppet/hieradata :hierarchy: - "nodes/%{::fqdn}" - common
The value under
:backends:defines that you are writing data in YAML, whereas:datadir:calls to the directory where the Hiera data will be stored. The:hierarchy:section denotes that your data will be saved in files under thenodedirectory, as a file named after the node’s FQDN. Acommonfile will also contain default variables.Ensure you are in the
/etc/puppet/directory, then create a directory forhieradataandnodes:sudo mkdir -p hieradata/nodesNavigate to the
nodesdirectory:cd hieradata/nodesUse the
puppet certcommand to list what nodes are available, then create a YAML file for each, using the FQDN as the file’s name:sudo puppet cert list --all sudo touch {ubuntuhost.example.com.yaml,centoshost.example.com.yaml}Open the first node’s configuration file to define the first database. In this example, the database is called
webdata1, withusernameandpasswordself-defined. Thegrantvalue is granting the user all access to the webdata1 database:- File: /etc/puppet/hieradata/nodes/ubuntuhost.example.com.yaml
1 2 3 4 5databases: webdata1: user: 'username' password: 'password' grant: 'ALL'
Repeat with the second server. In this example, the database is called
webdata2:- File: /etc/puppet/hieradata/nodes/centoshost.example.com.yaml
1 2 3 4 5databases: webdata2: user: 'username' password: 'password' grant: 'ALL'
Save and close the files.
Return to the
hieradatadirectory and create the filecommon.yaml. It will be used to define the defaultrootpassword for MySQL:- File: /etc/puppet/hieradata/common.yaml
1mysql::server::root_password: 'password'
The
common.yamlfile is used when a variable is not defined elsewhere. This means all servers will share the same MySQL root password. These passwords can also be hashed to increase security.Puppet now needs to know to use the information input in Hiera to create the defined database. Move to the
mysqlmodule directory and within themanifestsdirectory createdatabase.pp. Here you will define a class that will link themysql::dbresource to the Hiera data. It will also call themysql::serverclass, so it will not have to be included later:- File: /etc/puppet/modules/mysql/manifests/database.pp
1 2 3 4 5 6class mysql::database { include mysql::server create_resources('mysql::db', hiera_hash('databases')) }
Include
include mysql::databasewithin yoursite.ppfile for both nodes.
Create the PHP Module
Create the
phpdirectory in themodulespath, generating thefiles,manifests,templates, andexamplessub-folders afterward:sudo mkdir php cd php sudo mkdir {files,manifests,examples,templates}Create and open
init.pp. Because all that needs to be done is to install and ensure the PHP service is on and able to start on boot, all code will be contained in this file.Two packages will be installed: The PHP package and the PHP Extension and Application Repository. Use the
packageresource for this:- File: /etc/puppet/modules/php/manifests/init.pp
1 2 3 4 5 6 7 8 9 10 11 12class php { package { 'php': name: $phpname, ensure: present, } package { 'php-pear': ensure: present, } }
Because the
phppackage has different names on Ubuntu and CentOS, it will once again need to be defined with a parameter. However, because this is the only parameter we will be needing, it will be added directly to theinit.ppfile:- File: /etc/puppet/modules/php/manifests/init.pp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18class php { $phpname = $osfamily ? { 'Debian' => 'php5', 'RedHat' => 'php', default => warning('This distribution is not supported by the PHP module'), } package { 'php': name => $phpname, ensure => present, } package { 'php-pear': ensure => present, } }
Use the
serviceresource to ensure that PHP is on and set to start at boot:- File: /etc/puppet/modules/php/manifests/init.pp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24class php { $phpname = $osfamily ? { 'Debian' => 'php5', 'RedHat' => 'php', default => warning('This distribution is not supported by the PHP module'), } package { 'php': name => $phpname, ensure => present, } package { 'php-pear': ensure => present, } service { 'php-service': name => $phpname, ensure => running, enable => true, } }
Add
include phpto the hosts in yoursites.ppfile and runpuppet agent -ton your agent nodes to pull in any changes to your servers.
This page was originally published on
