R: Plots and graphs

Plotting in R is extremely easy.

plot (1:21)

rstudio_plotting_000

plot (1:8, main="TESTING",xlab="x",ylab="y")

rstudio_plotting_001

points(c(1,5),c(4,2), col="green")

rstudio_plotting_002

abline(h=3,col="red",lty=2)

rstudio_plotting_003

abline(h=1,col="yellow",lty=2)

rstudio_plotting_004

grid(col="purple")

rstudio_plotting_005

hist (1:21,col="orange")

rstudio_plotting_006

lines(c(2,4),c(5,3),col="blue")

rstudio_plotting_007

abline(h=3,col="red",lty=2)

Exporting and importing graphs

dev.copy(png,'myplot.png')
dev.off()

To list existing colors

> colors()
  [1] "white"                "aliceblue"            "antiquewhite"         "antiquewhite1"       
  [5] "antiquewhite2"        "antiquewhite3"        "antiquewhite4"        "aquamarine"          
  [9] "aquamarine1"          "aquamarine2"          "aquamarine3"          "aquamarine4"         
 [13] "azure"                "azure1"               "azure2"               "azure3"              
(...)
"violetred2"           "violetred3"          
[645] "violetred4"           "wheat"                "wheat1"               "wheat2"              
[649] "wheat3"               "wheat4"               "whitesmoke"           "yellow"              
[653] "yellow1"              "yellow2"              "yellow3"              "yellow4"             
[657] "yellowgreen"

Global changes for styles and colors

Adding texts to plots

text(11,11,"Regular text")

text(11,11, "Bigger text", cex=2)

text(5,5, "serif text", family="serif")

text(3,3 "mono text", family="mono")

text(7,7 "Sans text", family="sans")

 

Mathematic notation

demo(plotmath)

draw.plotmath.cell(expression(x != y), i, nr); i <- i + 1

> draw.plotmath.cell(expression(x < y), i, nr); i <- i + 1

> draw.plotmath.cell(expression(x <= y), i, nr); i <- i + 1

> draw.plotmath.cell(expression(x > y), i, nr); i <- i + 1

> draw.plotmath.cell(expression(x >= y), i, nr); i <- i + 1

> draw.plotmath.cell(expression(x %~~% y), i, nr); i <- i + 1

> draw.plotmath.cell(expression(x %=~% y), i, nr); i <- i + 1

> draw.plotmath.cell(expression(x %==% y), i, nr); i <- i + 1

> draw.plotmath.cell(expression(x %prop% y), i, nr); i <- i + 1

> draw.plotmath.cell(expression(x %~% y), i, nr); i <- i + 1

 

Installing Dataprotector 9 Agents on Debian 8

For some reason, dataprotector agents are released as an ISO image, with a +3000 lines shell script omnisetup.sh.

sudo ./omnisetup.sh -server myserver.myorg.es -install da

This lengthy script install dataprotector clients or server in several architectures:

  • osf1

  • hp-ux

  • SunOs and Solaris

  • AIX,

  • Linux x86, linux ia64

  • sco_sv

  • Darwin

  • PowerPC

For linux, it relays con rpm configuration. For Debian, the way to go would be alien.

Packages needed for Dataprotector agents (DA):

The only packages that are needed for the agents are:

  • OB2-TS-CORE-A.09.00-1.x86_64

  • OB2-CORE-A.09.00-1.x86_64

  • OB2-DA-A.09.00-1.x86_64

So, our first and naive aproach was a conversion with Alien and install them via dpkg -i.

for RPM in *.rpm; do sudo alien -c -k -d --fixperms $RPM; done

This led to an error as this three packages couldn’t be installed because we lacked some util called omnicc.

At this point, I tried running omnicc with bash -x, so that I could see what the long omnisetup was trying to do in my Debian machine.

bash -x ./omnisetup.sh -server myserver.myorg.es -install da

And then I noticed that, though only the above packages were installed, some others were uncompressed and used:

rpm2cpio /usr/local/share/Software_HP_DP_9.00_for_Linux_TD586-15021/linux_x86_64/DP_DEPOT/OB2-CORE-IS-A.09.00-1.x86_64.rpm 

cpio -id ./opt/omni/databases/utils/gpl/x86_64/linux-x86-64/utils.tar

cp ./opt/omni/databases/utils/gpl/x86_64/linux-x86-64/utils.tar .
(...)
rpm2cpio /usr/local/share/Software_HP_DP_9.00_for_Linux_TD586-15021/linux_x86_64/DP_DEPOT/OB2-TS-CFP-A.09.00-1.x86_64.rpm

cpio -id ./opt/omni/databases/vendor/ts_core/gpl/x86_64/linux-x86-64/A.09.00/packet.Z

PacketFullPath=/tmp/omni_tmp/opt/omni/databases/vendor/ts_core
/gpl/x86_64/linux-x86-64/A.09.00/packet.Z

(...)

rpm2cpio /usr/local/share/Software_HP_DP_9.00_for_Linux_TD586-15021/linux_x86_64/DP_DEPOT/OB2-DAP-A.09.00-1.x86_64.rpm

cpio -id ./opt/omni/databases/vendor/da/gpl/x86_64/linux-x86-64/A.09.00/packet.Z

PacketFullPath=/tmp/omni_tmp/opt/omni/databases/vendor/da/gpl/x86_64/linux-x86-64/A.09.00/packet.Z

(...)

At this point, I decided to stick to rpm installation, and use the omnisetup.sh script.

These are the files from the ISO image that we need to distribute to our Debian machines:

linux_x86_64 
│   ├── DP_DEPOT
│   │   ├── gpg-hpPublicKey.pub
│   │   ├── OB2-CFP-A.09.00-1.x86_64.rpm
│   │   ├── OB2-CORE-IS-A.09.00-1.x86_64.rpm
│   │   ├── OB2-DA-A.09.00-1.x86_64.rpm
│   │   ├── OB2-DAP-A.09.00-1.x86_64.rpm
│   │   ├── OB2-TS-CFP-A.09.00-1.x86_64.rpm
│   │   ├── OB2-TS-CORE-A.09.00-1.x86_64.rpm
│   │   └── OB2-TS-CS-A.09.00-1.x86_64.rpm
│   ├── scripts_linux_x86_64
│   │   ├── verify_gpg_lnx.sh
│   │   └── verify_gpg_lnx.sh.sig
│   └── SIG
│   └── DP_DEPOT
│   ├── OB2-CFP-A.09.00-1.x86_64.rpm.sig
│   ├── OB2-CORE-IS-A.09.00-1.x86_64.rpm.sig
│   ├── OB2-DA-A.09.00-1.x86_64.rpm.sig
│   ├── OB2-DAP-A.09.00-1.x86_64.rpm.sig
│   ├── OB2-TS-CFP-A.09.00-1.x86_64.rpm.sig
│   ├── OB2-TS-CORE-A.09.00-1.x86_64.rpm.sig
│   └── OB2-TS-CS-A.09.00-1.x86_64.rpm.sig
├── LOCAL_INSTALL
│   └── omnisetup.sh
├── Readme.txt

Manual installation:

apt-get install -y liblua5.1-0 xinetd rpm2cpio rpm 
sudo ./omnisetup.sh -server myserver.myorg.es -install da

Reconfigure xinetd to serve omni

cat /etc/xinetd.d/dataprotector 

omni stream tcp nowait root /opt/omni/lbin/inet inet -log /var/opt/omni/log/inet.log

Puppet installation

I am proud to present my own dataprotectoragent puppet module to avoid manual installation of this agent

puppet module install esterniclos-dataprotector agent

class {"dataprotectoragent":
      dataprotectorserver => "dataprotector.my.com",
    }

Available from

Troubleshooting

During this project, I encountered The package needs to be reinstalled, but I can’t find an archive for it error, and, luckily,  IhaveaPC awesome tutorial to get rid of it.

Instalación de host vmware esxi 6

Nuestra infraestructura está montada por blades HP con ilo. A traves de la ILO, montamos la imagen de ESX.

esx6.install004

El arranque desde CD:

 

esx6.install005

F11 para aceptar la licencia

esx6.install002

Hemos optado por unos blades sin discos, así que usamos las opciones de san-boot con una lun de 6GB para el propio sistema operativo

esx6.install006

esx6.install001

Configuración de red

Los esxi salen con una configuración dhcp, que, si no tenemos en nuestra infraestructura, tendremos que reconfigurar a Ips estáticas

esx6.config001

esx6.config002

VLAN:

esx6.config004Ipv4

esx6.config005

Servidores DNS

esx6.config006

Sufijo DNS

esx6.config007

Añadir al inventario vcenter

En nuestro caso, es una reinstalación de un servidor. Vamos a mantener su nombre, así que en la reconexión con el inventario, tendremos un error ssl.

esx6.config003

Stage patches

Usamos  vmware update manager

esx6.vum.001Otro reinicio…

Drivers

Últimamente, tras un cambio en cabinas, estamos teniendo muchos problemas con los drivers de los blades.

A pesar de que usamos la versión de ESX que paquetiza HP, tenemos que instalar manualmente, vía ssh los drivers:

esxcli software vib install -v  /vmfs/volumes/..../lpfc-10.5.70.0-1OEM.600.0.0.21
59203.x86_64.vib

Installation Result
   Message: The update completed successfully, but the system needs to be rebooted for the changes to be effective.
   Reboot Required: true
   VIBs Installed: EMU_bootbank_lpfc_10.5.70.0-1OEM.600.0.0.2159203
   VIBs Removed: Emulex_bootbank_lpfc_10.2.340.18-1OEM.550.0.0.1331820
   VIBs Skipped:

Host profile

Aplicamos el host profile que guarda toda la información de redes, configuraciones ntp, snmp…

Este es ya el último reinicio y el servidor está preparado para coger carga.

Vmware 6 ESXi host installation

Mount Iso image through Ilo. In this case, we are installing on a HP blade, so we are using ILO device to mount virtual CD.

esx6.install004

Boot from CD and run installer.

 

esx6.install005

F11 to accept license agreement

esx6.install002

Select disk to install. I our case, we use a 6 GB datastore to boot from disk. This allows us to change easily blades and keep server configuration untouched.

BTW, this blades were cheaper to buy as they have no disks.
esx6.install006

Wait for installer to end

esx6.install001

Boot.

First boot configuration

Vmware Esxi 6.0 tries to auto configure network.

esx6.config001

If DHCP is not present, static network settings have to be configured manually.

esx6.config002

VLAN:

esx6.config004Ipv4

esx6.config005

DNS server

esx6.config006

DNS suffix

esx6.config007

Add to vcenter inventory

If its a reinstallation, ssl certificates will have changes and a warning will show up.

esx6.config003

Stage patches

Using vmware update manager

esx6.vum.001This will lead to a server reboot.

Extra Drivers

For some reason, we have still to add HP drivers for our servers. Via ssh

esxcli software vib install -v  /vmfs/volumes/..../lpfc-10.5.70.0-1OEM.600.0.0.21
59203.x86_64.vib

Installation Result
   Message: The update completed successfully, but the system needs to be rebooted for the changes to be effective.
   Reboot Required: true
   VIBs Installed: EMU_bootbank_lpfc_10.5.70.0-1OEM.600.0.0.2159203
   VIBs Removed: Emulex_bootbank_lpfc_10.2.340.18-1OEM.550.0.0.1331820
   VIBs Skipped:

Apply host profile

Last reboot and host is ready to go!

Replace Github-linguist with source github version

First of all, we need to locate our github-linguist files which will be replaced. We will also need ruby-build and gcc.

find / -name languages.yml
apt-get install ruby-build gcc
ruby-build 2.1.0 /opt/gitlab/embedded/service/gem/ruby/2.1.0
cd /opt/gitlab/embedded/service/gem/ruby/2.1.0/gems/
wget https://github.com/github/linguist/archive/v4.7.5.tar.gz
tar -xvzf v4.7.5.tar.gz
mv linguist-4.7.5/ github-linguist-4.7.5
rm -f v4.7.5.tar.gz
# Install all ruby dependencies
bundle install

Generate samples.json:

After download from github,

bundle exec rake check_samples

Otherwise, we will face this error in logs

2016-03-30_07:49:38.08294 No such file or directory @ rb_sysopen - /opt/gitlab/embedded/service/gem/ruby/2.1.0/gems/github-linguist-4.7.5/lib/linguist/samples.json

Fetch all ace modes

bundle exec rake fetch_ace_modes

Problems with bundle install

gem install byebug -v '8.2.2'
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

Solved

apt-get install ruby-dev

When running bundle install, charlock_holmes would not be installed

gem install charlock_holmes -v '0.7.3'
(..)
checking for main() in -licui18n... no

Solved

apt-get install libicu-dev

We also had problems with rugged

gem install rugged -v '0.24.0'
(..)
checking for gmake... no
checking for cmake... no
checking for pkg-config... no
ERROR: CMake is required to build Rugged.

Solved

apt-get install cmake pkg-config
ln -s /usr/bin/make /usr/bin/gmake

 

 

Starting with R

Installation of R and R-studio in windows
  • https://cran.rediris.es/bin/windows/base/R-3.2.4revised-win.exe
  • https://download1.rstudio.org/RStudio-0.99.893.exe

Rconsole:

r.console.001

Proxy settings are configured at invocation command. I will use cygwin to start it:

 /cygdrive/c/Program\ Files/R/R-3.2.4revised/bin/x64/Rgui.exe  http_proxy=http:/localhost:8888/

You can also load values from internet explorer

 /cygdrive/c/Program\ Files/R/R-3.2.4revised/bin/x64/Rgui.exe  --internet2

Rconsole in linux

apt-get install r-recommended libxml2-dev  libcurl4-openssl-dev libssl-dev

wget https://download1.rstudio.org/rstudio-0.99.893-amd64.deb
sudo dpkg -i rstudio-0.99.893-amd64.deb

To Find which session file is freezing rstudio:

strace -f rstudio 2>&1 | grep open | grep home

Help. Sistema de ayuda

Online documentation for every package and function: http://www.rdocumentation.org/

help ("read.table")
?

Vignette the command used to open pdf help docs.

Installing new packages. Instalación de paquetes

To install new packages and dependencies

install.packages("curl", dependencies = TRUE)

To install more than one package at the same time, we can use C to make a vector of packages:

install.packages(c("curl","swirl","httr"), dependencies = TRUE)

Swirl package

Swirl()
Select_language()

Selección_001

Using and declaring variables.

myval <- 12

R simplest object  is a vector, it can be declared using c (combine)

myval <- c(12,21,2)

Variables value can be printed using print function or just their names:

print(myval) 
myval

To check the objects declared in a session

ls ()

Vectors

Defining a vector with a certain length and type

vector ("numeric", length = 23)

Create a vector with a repeating pattern

(rep(c(TRUE,FALSE),10))
 [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
[20] FALSE

Using a vector to index another vector.Return positions that are multiple of 4:

my_vector[c(FALSE,FALSE,FALSE,TRUE)]

Dates. Fechas

Great tutorial to work with dates: http://www.stat.berkeley.edu/~s133/dates.html

today <- Sys.Date()

Load data from a file

mydata <- read.table("mycommaseparatedvaluefile.csv", header=TRUE, sep=",", fileEncoding = "latin1")
view (Data)

 

sdf

Introducción a R

Instalación de R y R-studio en windows
  • https://cran.rediris.es/bin/windows/base/R-3.2.4revised-win.exe
  • https://download1.rstudio.org/RStudio-0.99.893.exe

 

r.console.001

Para la instalación de paquetes, es necesario configurar el proxy. En el ejemplo, se redirige el proxy a un puerto local con fiddler.

 /cygdrive/c/Program\ Files/R/R-3.2.4revised/bin/x64/Rgui.exe  http_proxy=http:/localhost:8888/

También se pueden recoger los valores desde Internet Explorer.

 /cygdrive/c/Program\ Files/R/R-3.2.4revised/bin/x64/Rgui.exe  --internet2

Instalación en linux. Debian 8.

apt-get install r-recommended libxml2-dev  libcurl4-openssl-dev libssl-dev

wget https://download1.rstudio.org/rstudio-0.99.893-amd64.deb
sudo dpkg -i rstudio-0.99.893-amd64.deb

Sistema de ayuda

http://www.rdocumentation.org/

help ("read.table")
?

También existe el comando Vignette para abrir los pdfs de ayuda que vienen integrados.

Instalación de paquetes nuevos

Instalación de nuevos paquetes con dependencias:

install.packages("curl", dependencies = TRUE)

Para instalar más de un paquete al mismo tiempo, se puede usar c (Combinar) con una lista de nombres de paquetes:

install.packages(c("curl","swirl","httr"), dependencies = TRUE)

Swirl package

Swirl()
Select_language()

Selección_001

Declaración de variables.

myval <- 12

Casi todos los datos simples que se van a usar, serán vectores.

myval <- c(12,21,2)

Para ver el valor, basta con usar print o poner el nombre del valor.

print(myval) 
myval

Los objetos existen en una memoria de sesión que se pueden consultar mediante el uso de ls.

ls ()

Vectores

Para definir un vector de tipo numérico con longitud determinada:

vector ("numeric", length = 23)

A los vectores se les puede asignar valores de inicio, con patrones repetitivos

(rep(c(TRUE,FALSE),10))
 [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
[20] FALSE

También se puede usar un vector para acceder a los valores de dentro del propio vector. En el ejemplo, se imprimirán por pantalla los valores que estén en posiciones múltiplos de 4.

my_vector[c(FALSE,FALSE,FALSE,TRUE)]

Fechas

http://www.stat.berkeley.edu/~s133/dates.html

today <- Sys.Date()

Leer un archivo:

mydata <- read.table("mycommaseparatedvaluefile.csv", header=TRUE, sep=",", fileEncoding = "latin1")
view (Data)

Using linux box to shrink and separate virtual disks

I have some virtual machines with partitions on their vmdk. This makes it terribly difficult to be resized.

I am going to use old dd linux command to copy all data.

In the hipervisor, I’m using a linux box, actually Debian box, to map all disks, and do all the block writing commands.

vmware_shrink2

I also have to take care of the first blocks of the disks, which contains the booting mark. Otherwise, I will have a copy of my data, but my disk won’t be bootable.

vmware_shrink1

Let’s get started.

I will assign to my linux box, all my disks. Old and new ones.

OS disk: Writing boot sector

#
# Copy boot blocks and old partition tables
#
dd if=/dev/sdb of=/dev/sdc bs=16 count=200

OS disk: writing data

I have to re-do partition table (using fdisk) and then copy all data.

As I copied from the original source disk the first sector, a fake partition table is also writen on my new OS disk. It’s time to repartition.

fdisk /dev/sdc
Welcome to fdisk (util-linux 2.25.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.
Command (m for help): p
Disk /dev/sdc: 15 GiB, 16106127360 bytes, 31457280 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xfe1387ed
Device Boot Start End Sectors Size Id Type
/dev/sdc1 * 63 31471334 31471272 15G 7 HPFS/NTFS/exFAT
/dev/sdc2 31471335 52452224 20980890 10G 7 HPFS/NTFS/exFAT

Delete second partition

Command (m for help): d 2
(...)
Command (m for help): p
(...)
Device Boot Start End Sectors Size Id Type
/dev/sdc1 * 63 31471334 31471272 15G 7 HPFS/NTFS/exFAT
(...)
Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

To write the data, the dd command has to be invoked partitions name (sdb1) and not entire disk (sdb). Entire disk was used just for the boot mark.

dd if=/dev/sdb1 of=/dev/sdc1

Data disk: writing data

I have 2 options here. As it is data, I can either write blocks (dd) or just ordinary file copying.

I created the partition table.

fdisk /dev/sdd

Command (m for help): t
Selected partition 1
Hex code (type L to list all codes): 7
Changed type of partition 'HPFS/NTFS/exFAT' to 'HPFS/NTFS/exFAT'.

Command (m for help): p
Disk /dev/sdd: 10 GiB, 10737418240 bytes, 20971520 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00c7e39c
Device Boot Start End Sectors Size Id Type
/dev/sdd1 2048 20971519 20969472 10G 7 HPFS/NTFS/exFAT

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

If we are going to use file system operations, I need to give it ntfs format:

apt-get install ntfs-3g
mkfs.ntfs /dev/sdd1

Now, it is time to mount both partitions and copy!

mkdir /mnt/old_data
mkdir /mnt/new_data
mount /dev/sdb2 /mnt/old_data/
mount /dev/sdd1 /mnt/new_data/
cp -rfp /mnt/old_data/* /mnt/new_data/

If ntfs permissions are not correctly written, you can use again old dd:

dd if=/dev/sdb2 of=/dev/sdd1

Vmware Update Manager 6

Actualización de ESXi mediante Vmware Update Manager

Requisitos previos:

La instalación de vum, sólo se puede realizar sobre una máquina windows. En nuestro caso, usaremos un servidor windows 2012 dedicado.

El instalador viene como parte de la ISO de vmware vcenter 6.0.0.

Antes de instalar, es necesario contar con .NET Framework 3.5 en la máquina :

En W2012, se puede instalar a través de la consola “Server Manager”añadiendo características, o con línea de comandos:

IMAGEN Server

dism.exe /online /enable-feature /featurename:NetFX3 /all

IMAGEN DSIM

En el caso de que la instalación devuelva el error 0x800f0906, es necesario cambiar la configuración de la política de grupo de windows

gpedit.msc

Computer Configuration > Administrative Templates > System >

Enable Specify stettings for optional component installation and co….

Check Contact Windows Update…

gpupdate /force

SqlServer 2012 : Odbc 32 bits

La base de datos que vamos a utilizar, es una instancia en SQL Server 2012. Para ello, se instala Microsoft SQL Server 2012 Native Client.

ms.quorum.error022

es necesario crear un ODBC de 32 bits

vum001

Especificamos la base de datos por defecto

vum003

Instalación del servidor Vmware Update Manager

Se monta el CD en la máquina virtual: VMware-VIMSetup-all-6.0.0-2656757.iso

Se instala el servidor de Vmware Update Manager. En este caso, son máquinas diferentes las que contienen Vmware Vcenter y Vmware Update Manager.vum004

Ambas máquinas deben tener visibilidad entre sí, en los puertos que se definen en el KB de vmware al igual que visibilidad con los servidores ESXi.

Instalación del cliente

En el cliente, se instala como un plugin dentro del cliente pesado de vmware.

En la misma ISO que el servidor Vmware Vmware-VIMSetup-all-6.0.0-2656757.iso, en la carpeta updateManager aparece

vum005

Es necesario instalar Vmware-UMClient.exe y reinicial el cliente vmware, para que aparezca como un plugin más

vum006

Crear un base line para descarga automatizada de parches

Crear un base line para servidores ESXi 6.00

vum007

dynamic

vum008

Sólo ESX 6

vum009

En nuestro caso, todos los ESX son iguales, por lo que es posible usar un único base line directamente para todo el servidor vmware

vum010

Parchear un servidor:

Vista en cliente

vum021

Pasos a realizar para parchear un servidor:

  • Stage. Es el paso en que se pasan los parches al servidor en concreto.

  • Poner en mantenimiento y aplicar los parches: “Remediate”

Puppet: Crear nuevos tipos para recursos

Un recurso (resource) en puppet es la unidad mínima de configuración.  Puppet viene con algunos recursos ya predefinidos (built-in) como son:

Los recursos, a la hora de instanciarse tienen un nombre propio de instancia, y se pueden invocar tantos como sean necesarios.

Es la diferencia más interesante respecto de una clase. La clase se aplica de forma única sobre el servidor; pero la clase puede tener N instancias de un recurso.

Vamos a ver cómo definir los recursos más simples, en el lenguaje declarativo de puppet.

Este ejemplo está sacado de puppetlabs:
# /etc/puppetlabs/puppet/modules/apache/manifests/vhost.pp
define apache::vhost (Integer $port, String[1] $docroot, String[1] $servername = $title, String $vhost_name = '*') {
  include apache # contains Package['httpd'] and Service['httpd']
  include apache::params # contains common config settings
  $vhost_dir = $apache::params::vhost_dir
  file { "${vhost_dir}/${servername}.conf":
    content => template('apache/vhost-default.conf.erb'),
      # This template can access all of the parameters and variables from above.
    owner   => 'www',
    group   => 'www',
    mode    => '644',
    require => Package['httpd'],
    notify  => Service['httpd'],
  }
}



Dado que está parametrizado, se pueden invocar N instancias distintas de vhost en nuestra clase.

Para invocar una instancia, es necesario ponerle un nombre y

<TYPE> { '<TITLE>':
  <ATTRIBUTE> => <VALUE>,
}

El ejemplo básico para el nuestro, sería en un servidor, pasar a definir varios vhosts distintos:

apache::vhost {'homepages':
  port    => 8081, # Becomes the value of $port
  docroot => '/var/www-testhost', # Becomes the value of $docroot
}

apache::vhost {'redmine':
  port    => 80, # Becomes the value of $port
  docroot => '/var/www/redmine', # Becomes the value of $docroot
}