PACKER - Poc 2022

Packer logo

Build Automated Machine Images

Create identical machine images for multiple platforms from a single source configuration.

Packer est un outil open source permettant de créer des images de machine identiques pour plusieurs plates-formes à partir d’une configuration source unique. Packer est léger, fonctionne sur tous les principaux systèmes d’exploitation et est très performant, créant des images machine pour plusieurs plates-formes en parallèle. Packer ne remplace pas la gestion de configuration comme Chef ou Puppet. En fait, lors de la création d’images, Packer peut utiliser des outils tels que Chef ou Puppet pour installer un logiciel sur l’image.

Why Packer?

Source: https://www.packer.io/

Rapid Infrastructure Deployment

Use Terraform to launch completely provisioned and configured machine instances with Packer images in seconds.

Multi-provider Portability

Identical images allow you to run dev, staging, and production environments across platforms.

Improved Stability

By provisioning instances from stable images installed and configured by Packer, you can ensure buggy software does not get deployed.

Increased Dev / Production Parity

Keep dev, staging, and production environments as similar as possible by generating images for multiple platforms at the same time.

Reliable Continuous Delivery

Generate new machine images for multiple platforms, launch and test, and verify the infrastructure changes work; then, use Terraform to put your images in production.

Appliance Demo Creation

Create software appliances and disposable product demos quickly, even with software that changes continuously.

Extending Packer with Plugins

Extend Packer’s functionality without modifying Packer core. Plugins are capable of adding these components:

  • Builders

  • Provisioners

  • Post-processors

  • Data sources

Documentation des plugins: https://www.packer.io/docs/plugins

Install Packer

Source: https://www.packer.io/downloads

Installing Packer on Linux

Ubuntu/Debian

curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
sudo apt-get update && sudo apt-get install packer

CentOS/RHEL

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install packer

Fedora

sudo dnf install -y dnf-plugins-core
sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/fedora/hashicorp.repo
sudo dnf -y install packer

Amazon Linux

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
sudo yum -y install packer

Homebrew

brew tap hashicorp/tap
brew install hashicorp/tap/packer

View Tutorials at HashiCorp Learn: https://learn.hashicorp.com/packer

Verifying the Installation

After installing Packer, verify the installation worked by opening a new command prompt or console, and checking that packer is available:

$ packer
Usage: packer [--version] [--help] <command> [<args>]

Available commands are:
    build           build image(s) from template
    console         creates a console for testing variable interpolation
    fix             fixes templates from old versions of packer
    fmt             Rewrites HCL2 config files to canonical format
    hcl2_upgrade    transform a JSON template into an HCL2 configuration
    init            Install missing plugins or upgrade plugins
    inspect         see components of a template
    validate        check that a template is valid
    version         Prints the Packer version

Or use the version option:

$ packer --version
Packer v1.7.10

If you get an error that packer could not be found, then your PATH environment variable was not set up properly. Please go back and ensure that your PATH variable contains the directory which has Packer installed.

Otherwise, Packer is installed and you’re ready to go!

Troubleshooting

On some distributions, there may be another tool named packer installed by default. The following error indicates that there is a name conflict.

$ packer
/usr/share/cracklib/pw_dict.pwd: Permission denied
/usr/share/cracklib/pw_dict: Permission denied

To fix this, create a symlink to packer that uses a different name like packer.io, or invoke the packer binary you want using its absolute path, e.g. /usr/local/packer.

Test on HyperV

Le fichier de configuration

Ici j’ai fait des tests de prise en main de packer sur Windows10 avec comme hyperviseur HyperV (hébergé sur la même machine).

Packer fonctionne avec des fichiers JSON ou Pkr HCL. Ici nous avons la nomenclature Pkr .HCL.

Ce fichier permet d’indiquer à packer la spécification de la VM, les options de build et d’output.

Ici nous installons un centos7

{
    "variable": "disk_size",
    "type": "string",
    "default": "25000"
}
{
    "variable": "memory",
    "type": "string",
    "default": "1024"
}
{
    "variable": "cpus",
    "type": "string",
    "default": "1"
}
{
    "variable": "output_directory",
    "type": "string",
    "default": "F:/HyperV-VM/packer/"
}
{
    "variable": "ssh_password",
    "type": "string",
    "default": "",
    "sensitive": true
}
{
    "variable": "switch_name",
    "type": "string",
    "default": "CommutExt"
}
{
    "variable": "vlan_id",
    "type": "string",
    "default": ""
}
{
    "variable": "vm_name",
    "type": "string",
    "default": "centos7"
}

La première partie concerne la définition de variable, que nous pouvons définir dans le même fichier ou appeler dans un fichier.

La seconde partie, appelée source, est une définition en avance de phase du provisioner (HyperV, VirtualBox, AWS…) qui sera ensuite appelé dans la partie build.

La troisième partie, build, appelle la source et les provisioner shell, file, ansible… qui permettent de peaufiner les installations.

IMPORTANT Les drivers/guest de virtualisation sont indispensables au bon fonctionnement de packer. Par exemple, sous HyperV, nous avons besoin que la VM embarque les drivers HyperV pour que Packer puisse récupérer son IP.

yum install -y hyperv-daemons hypervkvpd
systemctl enable hypervkvpd
systemctl start hypervkvpd

La partie Kickstart

The Red Hat Kickstart installation method is used by Fedora, Red Hat Enterprise Linux, and related Linux distributions to automatically perform unattended operating system installation and configuration.

Voici le kickstart que j’ai utilisé pour mes tests:

cat /var/www/html/ks1.cfg

# platform=x86, AMD64, or Intel EM64T
# version=DEVEL
# Install OS instead of upgrade
install
xconfig  --startxonboot
lang fr_FR.UTF-8
keyboard fr
rootpw admin
cdrom
firewall --disabled
selinux --permissive
auth  --useshadow  --passalgo=sha512
text
firstboot --disable
selinux --disabled
eula --agreed
services --enabled="chronyd"
services --enabled="sshd"
services --enabled="NetworkManager"
ignoredisk --only-use=sda
network --hostname centos7 --onboot yes --device eth0 --noipv6 --activate --bootproto dhcp --nameserver 8.8.8.8 --nameserver 1.1.1.1
reboot
timezone Europe/Paris --ntpservers=3.centos.pool.ntp.org,0.centos.pool.ntp.org,2.centos.pool.ntp.org,1.centos.pool.ntp.org
bootloader --location=mbr --boot-drive=sda
zerombr
clearpart --all --initlabel
part /boot/efi --fstype="vfat" --size=200
part /boot --fstype="ext4" --size=1024
part swap --fstype="swap" --size=16384
part / --fstype="ext4" --grow --size=1
repo --name=base --baseurl=http://mirror.centos.org/centos/7/os/$basearch/
repo --name=epel-release --baseurl=http://anorien.csc.warwick.ac.uk/mirrors/epel/7/$basearch/
repo --name=elrepo-kernel --baseurl=http://elrepo.org/linux/kernel/el7/$basearch/
repo --name=elrepo-release --baseurl=http://elrepo.org/linux/elrepo/el7/$basearch/
repo --name=elrepo-extras --baseurl=http://elrepo.org/linux/extras/el7/$basearch/

%packages
hyperv-daemons
hypervkvpd
@base
@compat-libraries
@core
chrony
mc
curl
wget
yum-priorities
yum-versionlock
yum-utils
yum-cron
openssh-server
openssh-clients
openssh
tree
vim
net-tools
%end

%post
systemctl enable sshd
systemctl set-default multi-user.target
systemctl disable initial-setup-text
systemctl disable initial-setup-graphical
sed -i 's/__all__ = \["EULAspoke"\]/__all__ = \["LicenseScreen"\]/' /usr/lib/python2.7/site-packages/initial_setup/tui/spokes/eula.py
echo "nameserver 8.8.8.8" >> /etc/resolv.conf
cp -pr /boot/efi/EFI/centos/* /boot/efi/EFI/BOOT/
systemctl enable hypervkvpd
systemctl start hypervkvpd
echo -e '%wheel ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
%end

user --name=packer --plaintext --password packer --groups=packer,wheel
sshkey --username=packer "ssh-rsa ***** corentinKey"

Meta

Auteur : Cbillet Date : 05/11/2024