Introduction à Packer
Aujourd’hui, je vais te parler de Packer. C’est un outil super cool développé et maintenu par Hashicorp qui te permet de créer des images système automatisées.
Tu sais quand tu veux déployer une application sur un serveur, il faut souvent installer et configurer tout un tas de trucs ? Et ben avec Packer, tu peux automatiser tout ça ! 🚀
Il te permet également de créer des images pour différents clouds publics ou systèmes de virtualisation. C’est super pratique pour les déploiements en production ! 💻
En gros, Packer c’est comme avoir un petit robot qui s’occupe de toutes les tâches fastidieuses pour toi 🤖
Dans cet article, je vais te montrer comment installer et utiliser Packer, et je te donnerai quelques exemples d’utilisation. Alors, prêt à automatiser tout ça ? 🚀
Installation de Packer
Les trois principales façon d’installer Packer :
- via le binaire de dépôt Git
- via les paquets de distribution Linux
- via Homebrew (pour MacOS)
Via le binaire
git clone https://github.com/hashicorp/packer.git
cd packer
make dev
Via les paquets linux
Pour Ubuntu / Debian :
sudo apt-get install packer
Pour Centos / Redhat :
sudo yum install packer
Installation sur Mac
brew install packer
Structure d’un projet Packer
Généralement la structure d’un projet packer ressemble à ça :
- packer-project/
- packer_files/
- scripts/
- install_software.sh
- configure_system.sh
- configs/
- config.json
- templates/
- template1.json
- template2.json
- builds/
- output1/
- output2/
- variables.json
- README.md
- Dans le dossier « packer_files« , tu vas mettre tous les fichiers nécessaires à la création de tes images.
- Le sous-dossier « scripts » contiendra les scripts shell que tu veux exécuter pour installer et configurer des logiciels sur l’image.
- Le sous-dossier « configs » contiendra les fichiers de configuration que tu veux copier sur l’image.
- Le sous-dossier « templates » contiendra les fichiers de template Packer qui définissent les paramètres de l’image.
- Le dossier « builds » est là où Packer va créer les images. Il contiendra un sous-dossier pour chaque image créée.
- Le fichier « variables.json » contiendra les variables utilisées dans tes templates Packer.
- Le fichier « README.md » est un fichier qui décrit le projet, il est utile pour les personnes qui vont travailler sur le projet pour comprendre comment ça fonctionne.
Cette structure est un exemple.
Il est possible d’adapter la structure à ses besoins il est important d’avoir une structure claire pour faciliter la maintenance et la compréhension du projet.
Utilisation de Packer
Maintenant que Packer est installé, on va pouvoir commencer à l’utiliser !
Les commandes du CLI
- packer build template_name: Cette commande permet de créer une image en utilisant le fichier de template spécifié.
- packer validate template_name: Pour valider un fichier de template pour vérifier qu’il est syntaxiquement correct.
- packer fix template_name : Cette commande corrige les erreurs d’un fichier de template.
- packer inspect template_name : Affiche les informations sur un fichier de template, comme les variables utilisées, les builders utilisés, etc.
- packer push template_name : Cette commande permet de pousser un fichier de template sur un dépôt distant.
- packer version
1er template
On va concevoir un template pour avoir une image Debian 10 qui intégrera une clé ssh publique et qui autorisera la connexion ssh à celui qui possède la clé privée.
On créée notre dossier packer :
mkdir packer-project
cd packer-project
mkdir -p packer_files/{configs,scripts,templates}
mkdir builds
touch variables.json README.md
On va donc générer la paire de clé SSH :
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" -f packer_files/configs/id_rsa -q -N ""
La clé packer_files/configs/id_rsa.pub sera intégré dans l’image et il suffira d’utiliser packer_files/configs/id_rsa pour se connecter en SSH à la machine.
Et on utilisera un fichier preseed.cfg pour configurer les paramètres d’installation de l’OS automatiquement
le fichier preseed.cfg :
# Source: https://www.debian.org/releases/buster/example-preseed.txt
#### Contents of the preconfiguration file (for buster)
### Localization
# Preseeding only locale sets language, country and locale.
d-i debian-installer/locale string en_US
# The values can also be preseeded individually for greater flexibility.
d-i debian-installer/language string fr
d-i debian-installer/country string FR
d-i debian-installer/locale string fr_FR.UTF-8
# Optionally specify additional locales to be generated.
#d-i localechooser/supported-locales multiselect en_US.UTF-8, nl_NL.UTF-8
# Keyboard selection.
d-i keyboard-configuration/xkb-keymap select fr(latin9)
d-i keyboard-configuration/variant select France
d-i console-setup/charmap select UTF-8
d-i console-setup/layout select France
# d-i keyboard-configuration/toggle select No toggling
d-i console-keymaps-at/keymap select fr-latin9
d-i debian-installer/keymap string fr-latin9
### Network configuration
# Disable network configuration entirely. This is useful for cdrom
# installations on non-networked devices where the network questions,
# warning and long timeouts are a nuisance.
#d-i netcfg/enable boolean false
# netcfg will choose an interface that has link if possible. This makes it
# skip displaying a list if there is more than one interface.
d-i netcfg/choose_interface select auto
# To pick a particular interface instead:
#d-i netcfg/choose_interface select eth1
# To set a different link detection timeout (default is 3 seconds).
# Values are interpreted as seconds.
#d-i netcfg/link_wait_timeout string 10
# If you have a slow dhcp server and the installer times out waiting for
# it, this might be useful.
#d-i netcfg/dhcp_timeout string 60
#d-i netcfg/dhcpv6_timeout string 60
# If you prefer to configure the network manually, uncomment this line and
# the static network configuration below.
#d-i netcfg/disable_autoconfig boolean true
# If you want the preconfiguration file to work on systems both with and
# without a dhcp server, uncomment these lines and the static network
# configuration below.
#d-i netcfg/dhcp_failed note
#d-i netcfg/dhcp_options select Configure network manually
# Static network configuration.
#
# IPv4 example
#d-i netcfg/get_ipaddress string 192.168.1.42
#d-i netcfg/get_netmask string 255.255.255.0
#d-i netcfg/get_gateway string 192.168.1.1
#d-i netcfg/get_nameservers string 192.168.1.1
#d-i netcfg/confirm_static boolean true
#
# IPv6 example
#d-i netcfg/get_ipaddress string fc00::2
#d-i netcfg/get_netmask string ffff:ffff:ffff:ffff::
#d-i netcfg/get_gateway string fc00::1
#d-i netcfg/get_nameservers string fc00::1
#d-i netcfg/confirm_static boolean true
# Any hostname and domain names assigned from dhcp take precedence over
# values set here. However, setting the values still prevents the questions
# from being shown, even if values come from dhcp.
d-i netcfg/get_hostname string vagrant-debian-buster
d-i netcfg/get_domain string example.com
# If you want to force a hostname, regardless of what either the DHCP
# server returns or what the reverse DNS entry for the IP is, uncomment
# and adjust the following line.
d-i netcfg/hostname string vagrant-debian-buster
# Disable that annoying WEP key dialog.
d-i netcfg/wireless_wep string
# The wacky dhcp hostname that some ISPs use as a password of sorts.
#d-i netcfg/dhcp_hostname string radish
# If non-free firmware is needed for the network or other hardware, you can
# configure the installer to always try to load it, without prompting. Or
# change to false to disable asking.
#d-i hw-detect/load_firmware boolean true
### Network console
# Use the following settings if you wish to make use of the network-console
# component for remote installation over SSH. This only makes sense if you
# intend to perform the remainder of the installation manually.
#d-i anna/choose_modules string network-console
#d-i network-console/authorized_keys_url string http://10.0.0.1/openssh-key
#d-i network-console/password password r00tme
#d-i network-console/password-again password r00tme
### Mirror settings
# If you select ftp, the mirror/country string does not need to be set.
#d-i mirror/protocol string ftp
d-i mirror/country string manual
d-i mirror/http/hostname string httpredir.debian.org
d-i mirror/http/directory string /debian
d-i mirror/http/proxy string
# Suite to install.
d-i mirror/suite string buster
# Suite to use for loading installer components (optional).
#d-i mirror/udeb/suite string testing
### Account setup
# Skip creation of a root account (normal user account will be able to
# use sudo).
d-i passwd/root-login boolean false
# Alternatively, to skip creation of a normal user account.
#d-i passwd/make-user boolean false
# Root password, either in clear text
d-i passwd/root-password password r00tme
d-i passwd/root-password-again password r00tme
# or encrypted using a crypt(3) hash.
#d-i passwd/root-password-crypted password [crypt(3) hash]
# To create a normal user account.
d-i passwd/user-fullname string Deploy User
d-i passwd/username string deploy
# Normal user's password, either in clear text
# Create vagrant user account.
d-i passwd/user-fullname string vagrant
d-i passwd/username string vagrant
d-i passwd/user-password password vagrant
d-i passwd/user-password-again password vagrant
d-i user-setup/allow-password-weak boolean true
d-i user-setup/encrypt-home boolean false
d-i passwd/user-default-groups vagrant sudo
d-i passwd/user-uid string 900
### Clock and time zone setup
# Controls whether or not the hardware clock is set to UTC.
d-i clock-setup/utc boolean true
# You may set this to any valid setting for $TZ; see the contents of
# /usr/share/zoneinfo/ for valid values.
d-i time/zone string Europe/Paris
d-i time/zone select Europe/Paris
# Controls whether to use NTP to set the clock during the install
d-i clock-setup/ntp boolean true
# NTP server to use. The default is almost always fine here.
#d-i clock-setup/ntp-server string ntp.example.com
### Partitioning
## Partitioning example
# If the system has free space you can choose to only partition that space.
# This is only honoured if partman-auto/method (below) is not set.
#d-i partman-auto/init_automatically_partition select biggest_free
# Alternatively, you may specify a disk to partition. If the system has only
# one disk the installer will default to using that, but otherwise the device
# name must be given in traditional, non-devfs format (so e.g. /dev/sda
# and not e.g. /dev/discs/disc0/disc).
# For example, to use the first SCSI/SATA hard disk:
d-i partman-auto/disk string /dev/sda
# In addition, you'll need to specify the method to use.
# The presently available methods are:
# - regular: use the usual partition types for your architecture
# - lvm: use LVM to partition the disk
# - crypto: use LVM within an encrypted partition
d-i partman-auto/method string lvm
# Use the whole disk
d-i partman-auto-lvm/guided_size string max
# If one of the disks that are going to be automatically partitioned
# contains an old LVM configuration, the user will normally receive a
# warning. This can be preseeded away...
d-i partman-lvm/device_remove_lvm boolean true
# The same applies to pre-existing software RAID array:
d-i partman-md/device_remove_md boolean true
# And the same goes for the confirmation to write the lvm partitions.
d-i partman-lvm/confirm boolean true
d-i partman-lvm/confirm_nooverwrite boolean true
# You can choose one of the three predefined partitioning recipes:
# - atomic: all files in one partition
# - home: separate /home partition
# - multi: separate /home, /var, and /tmp partitions
#d-i partman-auto/choose_recipe select atomic
# Or provide a recipe of your own...
# If you have a way to get a recipe file into the d-i environment, you can
# just point at it.
#d-i partman-auto/expert_recipe_file string /hd-media/recipe
# If not, you can put an entire recipe into the preconfiguration file in one
# (logical) line. This example creates a small /boot partition, suitable
# swap, and uses the rest of the space for the root partition:
#d-i partman-auto/expert_recipe string \
# boot-root :: \
# 40 50 100 ext3 \
# $primary{ } $bootable{ } \
# method{ format } format{ } \
# use_filesystem{ } filesystem{ ext3 } \
# mountpoint{ /boot } \
# . \
# 500 10000 1000000000 ext3 \
# method{ format } format{ } \
# use_filesystem{ } filesystem{ ext3 } \
# mountpoint{ / } \
# . \
# 64 512 300% linux-swap \
# method{ swap } format{ } \
# .
d-i partman-auto-lvm/new_vg_name string vg_system
d-i partman-lvm/vgcreate string vg_system
d-i partman-auto/expert_recipe string \
mypartitioning :: \
100 1000 20000 ext4 \
$primary{ } \
method{ lvm } \
device{ /dev/sda } \
vg_name{ vg_system } \
. \
250 250 250 ext2 \
$primary{ } $bootable{ } \
method{ format } format{ } \
use_filesystem{ } filesystem{ ext2 } \
mountpoint{ /boot } \
. \
100% 2048 100% linux-swap \
lv_name{ swap } \
method{ swap } format{ } \
$lvmok{ } in_vg{ vg_system } \
. \
5120 5120 5120 ext4 \
lv_name{ lv_root } \
method{ format } format{ } \
use_filesystem{ } filesystem{ ext4 } \
mountpoint{ / } \
$lvmok{ } in_vg{ vg_system } \
. \
2048 2048 2048 ext4 \
lv_name{ lv_tmp } \
method{ format } format{ } \
use_filesystem{ } filesystem{ ext4 } \
mountpoint{ /tmp } \
$lvmok{ } in_vg{ vg_system } \
. \
2048 2048 2048 ext4 \
lv_name{ lv_opt } \
method{ format } format{ } \
use_filesystem{ } filesystem{ ext4 } \
mountpoint{ /opt } \
$lvmok{ } in_vg{ vg_system } \
. \
9000 9000 9000 ext4 \
lv_name{ lv_var } \
method{ format } format{ } \
use_filesystem{ } filesystem{ ext4 } \
mountpoint{ /var } \
$lvmok{ } in_vg{ vg_system } \
. \
# The full recipe format is documented in the file partman-auto-recipe.txt
# included in the 'debian-installer' package or available from D-I source
# repository. This also documents how to specify settings such as file
# system labels, volume group names and which physical devices to include
# in a volume group.
# This makes partman automatically partition without confirmation, provided
# that you told it what to do using one of the methods above.
d-i partman-partitioning/confirm_write_new_label boolean true
d-i partman/choose_partition select finish
d-i partman/confirm boolean true
d-i partman/confirm_nooverwrite boolean true
# When disk encryption is enabled, skip wiping the partitions beforehand.
#d-i partman-auto-crypto/erase_disks boolean false
## Partitioning using RAID
# The method should be set to "raid".
#d-i partman-auto/method string raid
# Specify the disks to be partitioned. They will all get the same layout,
# so this will only work if the disks are the same size.
#d-i partman-auto/disk string /dev/sda /dev/sdb
# Next you need to specify the physical partitions that will be used.
#d-i partman-auto/expert_recipe string \
# multiraid :: \
# 1000 5000 4000 raid \
# $primary{ } method{ raid } \
# . \
# 64 512 300% raid \
# method{ raid } \
# . \
# 500 10000 1000000000 raid \
# method{ raid } \
# .
# Last you need to specify how the previously defined partitions will be
# used in the RAID setup. Remember to use the correct partition numbers
# for logical partitions. RAID levels 0, 1, 5, 6 and 10 are supported;
# devices are separated using "#".
# Parameters are:
# <raidtype> <devcount> <sparecount> <fstype> <mountpoint> \
# <devices> <sparedevices>
#d-i partman-auto-raid/recipe string \
# 1 2 0 ext3 / \
# /dev/sda1#/dev/sdb1 \
# . \
# 1 2 0 swap - \
# /dev/sda5#/dev/sdb5 \
# . \
# 0 2 0 ext3 /home \
# /dev/sda6#/dev/sdb6 \
# .
# For additional information see the file partman-auto-raid-recipe.txt
# included in the 'debian-installer' package or available from D-I source
# repository.
# This makes partman automatically partition without confirmation.
d-i partman-md/confirm boolean true
d-i partman-partitioning/confirm_write_new_label boolean true
d-i partman/choose_partition select finish
d-i partman/confirm boolean true
d-i partman/confirm_nooverwrite boolean true
## Controlling how partitions are mounted
# The default is to mount by UUID, but you can also choose "traditional" to
# use traditional device names, or "label" to try filesystem labels before
# falling back to UUIDs.
#d-i partman/mount_style select uuid
### Base system installation
# Configure APT to not install recommended packages by default. Use of this
# option can result in an incomplete system and should only be used by very
# experienced users.
#d-i base-installer/install-recommends boolean false
# The kernel image (meta) package to be installed; "none" can be used if no
# kernel is to be installed.
#d-i base-installer/kernel/image string linux-image-686
### Apt setup
# You can choose to install non-free and contrib software.
#d-i apt-setup/non-free boolean true
#d-i apt-setup/contrib boolean true
# Uncomment this if you don't want to use a network mirror.
#d-i apt-setup/use_mirror boolean false
# Select which update services to use; define the mirrors to be used.
# Values shown below are the normal defaults.
#d-i apt-setup/services-select multiselect security, updates
#d-i apt-setup/security_host string security.debian.org
# Additional repositories, local[0-9] available
#d-i apt-setup/local0/repository string \
# http://local.server/debian stable main
#d-i apt-setup/local0/comment string local server
# Enable deb-src lines
#d-i apt-setup/local0/source boolean true
# URL to the public key of the local repository; you must provide a key or
# apt will complain about the unauthenticated repository and so the
# sources.list line will be left commented out
#d-i apt-setup/local0/key string http://local.server/key
# By default the installer requires that repositories be authenticated
# using a known gpg key. This setting can be used to disable that
# authentication. Warning: Insecure, not recommended.
#d-i debian-installer/allow_unauthenticated boolean true
# Uncomment this to add multiarch configuration for i386
#d-i apt-setup/multiarch string i386
### Package selection
tasksel tasksel/first multiselect standard, ssh-server
# Individual additional packages to install
d-i pkgsel/include string build-essential ssh python
# Whether to upgrade packages after debootstrap.
# Allowed values: none, safe-upgrade, full-upgrade
d-i pkgsel/upgrade select safe-upgrade
# Some versions of the installer can report back on what software you have
# installed, and what software you use. The default is not to report back,
# but sending reports helps the project determine what software is most
# popular and include it on CDs.
popularity-contest popularity-contest/participate boolean false
### Boot loader installation
# Grub is the default boot loader (for x86). If you want lilo installed
# instead, uncomment this:
#d-i grub-installer/skip boolean true
# To also skip installing lilo, and install no bootloader, uncomment this
# too:
#d-i lilo-installer/skip boolean true
# This is fairly safe to set, it makes grub install automatically to the MBR
# if no other operating system is detected on the machine.
d-i grub-installer/only_debian boolean true
# This one makes grub-installer install to the MBR if it also finds some other
# OS, which is less safe as it might not be able to boot that other OS.
d-i grub-installer/with_other_os boolean true
# Due notably to potential USB sticks, the location of the MBR can not be
# determined safely in general, so this needs to be specified:
d-i grub-installer/bootdev string /dev/sda
# To install to the first device (assuming it is not a USB stick):
#d-i grub-installer/bootdev string default
# Alternatively, if you want to install to a location other than the mbr,
# uncomment and edit these lines:
#d-i grub-installer/only_debian boolean false
#d-i grub-installer/with_other_os boolean false
#d-i grub-installer/bootdev string (hd0,1)
# To install grub to multiple disks:
#d-i grub-installer/bootdev string (hd0,1) (hd1,1) (hd2,1)
# Optional password for grub, either in clear text
#d-i grub-installer/password password r00tme
#d-i grub-installer/password-again password r00tme
# or encrypted using an MD5 hash, see grub-md5-crypt(8).
#d-i grub-installer/password-crypted password [MD5 hash]
# Use the following option to add additional boot parameters for the
# installed system (if supported by the bootloader installer).
# Note: options passed to the installer will be added automatically.
#d-i debian-installer/add-kernel-opts string nousb
### Finishing up the installation
# During installations from serial console, the regular virtual consoles
# (VT1-VT6) are normally disabled in /etc/inittab. Uncomment the next
# line to prevent this.
d-i finish-install/keep-consoles boolean true
# Avoid that last message about the install being complete.
d-i finish-install/reboot_in_progress note
# This will prevent the installer from ejecting the CD during the reboot,
# which is useful in some situations.
#d-i cdrom-detect/eject boolean false
# Prevent asking for more installation media
d-i apt-setup/cdrom/set-first boolean false
# This is how to make the installer shutdown when finished, but not
# reboot into the installed system.
#d-i debian-installer/exit/halt boolean true
# This will power off the machine instead of just halting it.
#d-i debian-installer/exit/poweroff boolean true
### Preseeding other packages
# Depending on what software you choose to install, or if things go wrong
# during the installation process, it's possible that other questions may
# be asked. You can preseed those too, of course. To get a list of every
# possible question that could be asked during an install, do an
# installation, and then run these commands:
# debconf-get-selections --installer > file
# debconf-get-selections >> file
#### Advanced options
### Running custom commands during the installation
# d-i preseeding is inherently not secure. Nothing in the installer checks
# for attempts at buffer overflows or other exploits of the values of a
# preconfiguration file like this one. Only use preconfiguration files from
# trusted locations! To drive that home, and because it's generally useful,
# here's a way to run any shell command you'd like inside the installer,
# automatically.
# This first command is run as early as possible, just after
# preseeding is read.
#d-i preseed/early_command string anna-install some-udeb
# This command is run immediately before the partitioner starts. It may be
# useful to apply dynamic partitioner preseeding that depends on the state
# of the disks (which may not be visible when preseed/early_command runs).
#d-i partman/early_command \
# string debconf-set partman-auto/disk "$(list-devices disk | head -n1)"
# This command is run just before the install finishes, but when there is
# still a usable /target directory. You can chroot to /target and use it
# directly, or use the apt-install and in-target commands to easily install
# packages and run commands in the target system.
d-i preseed/late_command string apt-install zsh lv vim parted
Mets ce fichier dans le dossier packer_files/configs
Le script qui s’exécuteras juste après l’installation de l’OS qui ajoutera la clé ssh dans les clés autorisées à se connecter en SSH :
#!/bin/sh
# Deploy keys to allow all nodes to connect each others as root
mkdir /root/.ssh/
mkdir -p /home/vagrant/.ssh/
mv /tmp/id_rsa* /root/.ssh/
cp /root/.ssh/id_rsa* /home/vagrant/.ssh/
chmod 400 /root/.ssh/id_rsa*
chmod 400 /home/vagrant/.ssh/id_rsa*
chown root:root /root/.ssh/id_rsa*
chown vagrant:vagrant /home/vagrant/.ssh/id_rsa*
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
cat /home/vagrant/.ssh/id_rsa.pub >> /home/vagrant/.ssh/authorized_keys
chmod 400 /root/.ssh/authorized_keys
chmod 400 /home/vagrant/.ssh/authorized_keys
chown root:root /root/.ssh/authorized_keys
chown vagrant:vagrant /home/vagrant/.ssh/authorized_keys
# Install updates and curl
apt update -y
apt install -y curl wget
# Apt cleanup.
apt autoremove -y
apt update -y
# Blank netplan machine-id (DUID) so machines get unique ID generated on boot.
truncate -s 0 /etc/machine-id
rm /var/lib/dbus/machine-id
ln -s /etc/machine-id /var/lib/dbus/machine-id
## add vagrant to sudo
echo "vagrant ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
Copie ce code dans le fichier packer_files/scripts/script_start.sh
Ce script permet d’utiliser la clé privé id_rsa pour se connecter en SSH à l’utilisateur vagrant et root.
Il remet aussi à zéro l’identifiant de la machine pour générer un identifiant unique lors du démarrage.
Voici enfin le fameux fichier template :
{
"builders": [
{
"boot_command": [
"<esc><wait>",
"install <wait>",
" preseed/url=http://{{ .HTTPIP }}:{{ .HTTPPort }}/preseed.cfg <wait>",
"debian-installer=en_US.UTF-8 <wait>",
"auto <wait>",
"locale=en_US.UTF-8 <wait>",
"kbd-chooser/method=us <wait>",
"keyboard-configuration/xkb-keymap=us <wait>",
"netcfg/get_hostname={{ .Name }} <wait>",
"netcfg/get_domain=local <wait>",
"fb=false <wait>",
"debconf/frontend=noninteractive <wait>",
"console-setup/ask_detect=false <wait>",
"console-keymaps-at/keymap=fr <wait>",
"grub-installer/bootdev=/dev/sda <wait>",
"<enter><wait>"
],
"cpus": "1",
"disk_size": "30000",
"format": "ova",
"guest_additions_mode": "upload",
"guest_os_type": "Debian_64",
"headless": "false",
"http_directory": "packer_files/configs",
"iso_checksum": "sha256:133430141272d8bf96cfb10b6bfd1c945f5a59ea0efc2bcb56d1033c7f2866ea",
"iso_target_path": "./iso/debian-10.11.0-amd64-netinst.iso",
"iso_url": "https://cdimage.debian.org/cdimage/archive/10.11.0/amd64/iso-cd/debian-10.11.0-amd64-netinst.iso",
"memory": "1024",
"shutdown_command": "echo {{user `ssh_pass`}} | sudo -S shutdown -P now",
"ssh_password": "{{user `ssh_pass`}}",
"ssh_timeout": "20m",
"ssh_username": "{{user `ssh_user`}}",
"type": "virtualbox-iso",
"output_directory": "builds/",
"vm_name": "Debian10-packer"
}
],
"variables": {
"domain": "local",
"hostname": "Debian10-packer",
"ssh_pass": "vagrant",
"ssh_user": "vagrant"
},
"provisioners": [
{
"destination": "/tmp/",
"source": "packer_files/configs/id_rsa.pub",
"type": "file"
},
{
"type": "shell",
"script": "packer_files/scripts/script_start.sh",
"execute_command": "echo {{user `ssh_pass`}} | sudo -S -E sh -c '{{ .Vars }} {{ .Path }}'",
"pause_before": "10s",
"timeout": "10s"
}
],
"post-processors": [
{
"type": "vagrant",
"keep_input_artifact": true,
"output": "builds/debian10-packer.box"
}
]
}
Places ce code dans packer_files/templates/virtualbox-debian10.json
On lance la commande suivante pour lancer la création de l’image :
packer build packer_files/templates/virtualbox-debian10.json
Packer utilisera alors Virtualbox pour créer l’image puis une fois terminée, tu obtiendras la vagrant box et le fichier OVA de l’image dans le dossier builds/.
Template avec variables séparées
Si on souhaite séparer les variables du template, on peut les placer dans un fichier comme ci-dessus et l’appeler au moment du build.
fichier variables.json :
{
"domain": "local",
"hostname": "Debian10-packer",
"ssh_pass": "vagrant",
"ssh_user": "vagrant",
"output_directory": "builds/",
"http_directory": "packer_files/configs",
"iso_target_path": "./iso/debian-10.11.0-amd64-netinst.iso",
"iso_url": "https://cdimage.debian.org/cdimage/archive/10.11.0/amd64/iso-cd/debian-10.11.0-amd64-netinst.iso",
"iso_checksum": "sha256:133430141272d8bf96cfb10b6bfd1c945f5a59ea0efc2bcb56d1033c7f2866ea"
}
Dans le template on utilise les variables comme cela :
"ssh_username": "{{user `ssh_user`}}",
Commande pour build avec le fichier de variables :
packer build -var-file=variables.json chemin/vers/template.json
Exemples d’utilisation
- Créer des images de machines virtuelles préconfigurées. Par exemple, tu peux créer une image de VM avec un système d’exploitation spécifique, des outils de développement préinstallés et des paramètres de sécurité définis. 🚀
- Intégration avec les outils de déploiement : Packer peut être utilisé en conjonction avec des outils de déploiement comme Ansible ou Terraform pour automatiser encore plus le déploiement de tes infrastructures. Tu peux utiliser Packer pour créer des images de VM, puis utiliser Ansible pour configurer ces VMs et les déployer sur des environnements de production. 💻
- Automatisation de la construction de machines virtuelles pour les tests : tu peux utiliser Packer pour créer des images de machines virtuelles pour tes tests, de cette façon tu es certain que tes tests ont lieu sur une configuration standardisée. Cela facilite la reproductibilité des résultats et te permet de détecter les problèmes plus rapidement. 🧪
- Création d’images pour le cloud : Packer peut également être utilisé pour créer des images de machines virtuelles pour le cloud. Cela te permet de déployer rapidement des machines virtuelles dans le cloud avec des configurations standardisées. 🌩️
Pour en savoir plus sur Packer et ses fonctionnalités, je te conseille de jeter un coup d’oeil à la documentation officielle : https://www.packer.io/docs/ 🤓.
Et si tu ne connais pas Vagrant fonce sur cet article, Vagrant associé à Packer permet de concevoir des environnements de développement aux petits oignons.