When dealing with Hybrid or multi-cloud environments, you would need to have an identical machine images for multiple platforms from a single source configuration. That’s were Packer comes into play.
To get started, find the appropriate package for your system and download Packer:
1 | curl https://releases.hashicorp.com/packer/1.2.2/packer_1.2.2_darwin_amd64.zip -O /usr/local/bin/packer |
With Packer installed, let’s just dive right into it and bake our AMI with a preinstalled Docker Engine in order to build a Swarm or Kubernetes cluster and avoid cold-start of node machines.
Packer is template-driven, templates are written in JSON format:
1 | { |
The template is divided into 3 sections:
- variables: Custom variables that can be overriden during runtime by using the -var flag. In the above snippet, we’re specifying the AWS region.
- builders: You can specify multiple builders depending on the target platforms (EC2, VMware, Google Cloud, Docker …).
- provisioners: You can pass a shell script or use configuration managements tools like Ansible, Chef, Puppet or Salt to provision the AMI and install all required packages and softwares.
Packer will use an existing Amazon Linux Image “Gold Image” from the marketplace and install the latest Docker community edition using the following Bash script:
1 | #/bin/sh |
Note: You can avoid hardcoding the Gold Image ID in the template by using the source_ami_filter attribute.
Before we take the template and build an image from it, let’s validate the template by running:
1 | packer validate ami.json |
Now that we have our template file and bash provisioning script ready to go, we can issue the following command to build our new AMI:
1 | packer build ami.json |
This will chew for a bit and finally output the AMI ID:
Next, create a new EC2 instance based on the AMI:
1 | aws ec2 run-instances --image-id ami-3fbc1940 |
Then, connect to your instance via SSH and type the following command to verify Docker latest release is installed:
Simple right ? Well, you can go further and setup a CI/CD pipeline to build your AMIs on every push, recreate your EC2 instances with the new AMIs and rollback in case of failure.
Drop your comments, feedback, or suggestions below — or connect with me directly on Twitter @mlabouardy.