Dear Reader, do you also share the struggles of a DevOps life? Then you probably know the importance of the right tools - tools that we would love to be intuitive, well-organised, easy to use. It often happens that we can’t choose our favourite tools to work with. However, it shouldn’t stop you from testing by yourself! That’s what I do in my free time and I want to share with you what I got to know recently.
Using Packer by HashiCorp
HashiCorp may sound familiar to you, Dear Reader, because of my April article on creating an EC2 instance with Terraform - tool provided exactly by HashiCorp.
Packer is a tool for automated creation of machine images that allows us to provision our 'Packer images' with software of our choice.
Packer supports a lot of Builders, such as Amazon, Docker, VMware, Vagrant and much more. Today, I am going to show an example of using Docker Builder.
Prerequisites
- Installed Packer
- Basic knowledge of Docker
We are going to start with our own Docker image that will be provisioned with Terraform and AWSCLI.The templates are written in JSON so it’s easy to maintain them.
// example.json
{
"builders": [
{
"commit": "true"
"image": "ubuntu:18.04",
"type": "docker"
}
],
"post-processors": [
[
{
"repository": "zelaskov/packer-example",
"tags": ["0.11"],
"type": "docker-tag"
}
]
],
"provisioners": [
{
"script": "terraform.sh",
"type": "shell"
},
{
"script": "awscli.sh",
"type": "shell"
}
]
}
It’s pretty simple - we use Docker Builder with Ubuntu 18.04 as a base image. We are using docker-tag post-processor to tag our image and shell provisioners to run our scripts.
# terraform.sh
apt-get update
apt-get install wget -y
apt-get install unzip -y
wget https://releases.hashicorp.com/terraform/0.12.28/terraform_0.12.28_linux_amd64.zip
unzip terraform_0.12.28_linux_amd64.zip
rm -rf terraform_0.12.28_linux_amd64.zip
mv terraform /usr/local/bin/
We are installing all necessary tools for Terraform.
# awscli.sh
apt install python3 -y
apt install python3-pip -y
pip3 install --upgrade pip
pip3 install awscli
Same story as above, we are installing python3 and pip3 because it’s required for awscli.
Right now we can build our image!
You can firstly validate your template with command packer validate name_of_the_template
packer build example.json
We are going to see the packer output in the console.
Our build is successfully finished!
Let’s check if our provisioning went fine, as well!
docker run -it image_id
We can see that packer successfully installed software!
Packer is especially useful when we want to create our custom AMI image or while using Vagrant.
Here, I will redirect you to Packer AWS tutorial if you are eager to practice some more!
You can also check my repo if you run into any issues: https://github.com/zelaskov/packer-example