Packer is an open source tool created by Mitchell Hashimoto. It allows you to build virtual machine images for different platforms. For example: Amazon, VMware or VirtualBox. Thanks to Packer you can store your virtual machine set up in single json file with some bash scripts and keep it in source code repository. Packer works on different operating systems - also on Windows :)
Packer vs configuration management tools
In fact, Packer could replace available CM tools like Chef, Ansible or Salt. However, better way is to install CM tool during building an image and then use it to the hard work. For example you can create a bash script which installs Chef with proper keys and then registers the node to your Chef Server.
Prerequisites
Packer needs VirtualBox to build the image. So, you should install the following:
Let’s create a base image using Packer and then test if it is usable using Vagrant.
Preparation
Firstly, you need to prepare preseed and json file for your image.
Preseed contains very low level information of the OS, such as locale settings, time/zone and clock, network, disks settings, grub amd many more. For this example I would recommend to use one from Mitchell Hashimoto:
Json file contains some information about the image (iso url, checksum), ssh user and also provisioners - where you run your scripts. Let’s create a simple json file which will allow us to use it in Vagrant:
Now, it’s time to create two bash scripts (I recommend to create new directory scripts for them):
vagrant.sh which will set up settings for vagrant user.
virtualbox.sh which will set up required settings for VirtualBox
Building a VM image
The json file and bash scripts are ready. Now, it’s time to build the image. To do this you can call:
This can take a couple of minutes. Here you can find the output of packer build execution.
Testing a VM image
In the next, you can test if your image is usable. To do that, you can add freshly create image to ~/.vagrant.d/boxes. You can call:
It should generate similar output:
Your box is ready to use by Vagrant. Let’s create Vagrantfile which will use it:
This will produce a message that Vagrantfile has been created:
After that you can call vagrant up to test box built by Packer. This should produce this output.
Summary
Thanks to Packer we can enable Infrastructure as a Code from the beginning in our project. We can store virtual machine image in source code repository. We can also automate the process of building and testing the image using Continuous Integration system such as Jenkins or TeamCity.