Build Docker Images with Ansible + Vagrant So I am working on a research project and I am trying to automatically generate specific environments on different virtualization techniques.  

So, first I made a Vagrantfile that pulls an Ubuntu image and then runs an Ansible  playbook. I have a playbook that defines everything for my environment.
Which means it copies files, installs and configures everything.
For VirtualBox this is no problem, - it spins up my environment in VirtualBox.

Now I want to do this exact same thing, but on Docker. Normally one would write a docker file to define the environment. What I want to do is re-use the Ansible script to define the environment (despite being a bit counter-intuitive). While there seems to be some support for Docker in Vagrant - what is the best way to achieve what I want. I want to create a Docker Container - exactly how specified in the Ansible playbook. (Basically re-using the playbook I also used to setup VirtualBox). The output should then be a docker image that I can just start with docker run.

Whats the best way to do this? What do I have to look out for?  

My current idea is the following:

1) Setup a VM with Vagrant.
2) Install Ansible and Docker in that VM.
3) Create a new Docker Image with Ansible. It just defines the Container OS and maybe opens a port so Ansible can SSH into the container?
4) Run the playbook in the container to configure everything.
5) Package the entire thing as a new image
6) Transfer packaged docker image to the host machine
If it's within scope, I would use Packer to build the artifacts.


Write a Packer template using the builders that you want:


Vagrant builder for the Vagrant image
Docker builder for the Docker image.

Use the same Ansible playbook as you already have to provision each of the builders.


Note that you need to make sure that the Ansible playbook will work in both types of virtualised environments.

This has the benefit of producing arbitrary types of artifacts, based off of a single input. You can use a single workflow for both the Vagrant and the Docker images, and they will be built off of the same state of the codebase (i.e. git hash).