Building docker image with packer and ansible

Ansible is the one of most popular tool for deploying apps, configuration management and automation where you can handle repetitive tasks.

Read here to get better understanding of docker.

Currently ansible is what we use to deploy our applications on AWS machines .

Ansible helps us provision our machines with required libraries, packages, files, repositories, applications and services.

Disclaimer: Ansible knowledge is must to understand this article.

Ansible playbook is yaml file containing all the configuration to provision a new machine.

Docker Image: Standard way to create a docker image is by using Dockerfile. Here’s a sample docker file

What is Packer

Packer is a tool for creating images for multiple platforms from a single source configuration. Packer is lightweight, runs on every major operating system, and is highly performant, creating machine images for multiple platforms in parallel.

Dockerfile is limited to Docker, packer creates images for all popular container platforms. Its much easier to create packer configuration file as well (json being one of the reason). It embraces use of frameworks such as Ansible, puppet, so creating Image from existing configuration is cake-walk. And perfect for our use-case too.

So if you don’t want to stick to docker for rest of your life, packer is the tool for you.

Follow this guide to install packer

Now that packer is installed, Create a json file where you will define all the configuration

sample.json file

"type": "docker",
"image": "ubuntu:16.04",
"commit": true
"type": "ansible-local",
"playbook_file": "./ansible-sample.yml",
"playbook_dir": "."
"post-processors": [
"type": "docker-tag",
"repository": "",
"tag": "image_tag"

Run $ ./packer build sample.json

This command will create a docker image using ansible-sample.yml playbook and will push image to docker repository.