Re-using Ansible playbooks to Build Docker Containers

DockerStarted working on a small side project to build a production distributed system in a developers laptop. I decided it was an excellent reason to use Docker 🐳.

Docker has it’s own way to build containers, by using Dockerfile‘s. Dockerfile’s are well thought out and their capabilities are throughly documented. I urge you to check it out if you haven’t yet.

However the thing is, the production environment we have, already has Ansible scripts to build our servers. Does it reallyAnsible make sense to maintain now two types of documents? One Ansible for production and one of Docker for development?

Let us check on how to build these containers using Ansible.

The fastest way to be able to re-use the Ansible playbooks will be running them from within the containers themselves. The idea should come familiar from my previous post of provisioning Vagrant VM’s with Ansible.

The first order of business would be creating a directory structure like the following:

The important thing is that the Dockerfile needs to be above the directory structure. As any references in Dockerfile like “../ansible” won’t work due to security reasons set by Docker. To overcome this one might use  a symlink.

Once you have set the Dockerfile add the following lines to it:

This Dockerfile will install ansible to the container, copy our ansible files to said container and run the playbook. You can run the build process with the following command:

This will build the container “docker-container“.

So should we use Ansible to build our containers? Probably not. The author of Ansible agrees with this. Ansible should probably be used for setting the build environment, deployment and testing stages of the building of Docker containers.

Creating the Dockerfile’s are pretty simple. And once these files are created there should be little or no change. The apps deployed within the containers might change. However, my belief is, deployments can be or should be handled by Ansible. The deployment scripts should be the ones that get re-used.

I hope to write more of my thoughts of deployments and builds as I have been moving towards the DevOps world. I know I definitely have a lot to learn. I enjoy each moment of it. So, hope you like this.

As always,

Have fun!