Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Ansible playbook using Docker

Tags:

I'm new to ansible (and docker). I would like to test my ansible playbook before using it on any staging/production servers.

Since I don't have access to an empty remote server, I thought the easiest way to test would be to use Docker container and then just run my playbook with the Docker container as the host.

I have a basic DockerFile that creates a standard ubuntu container. How would I configure the ansible hosts in order to run it against the docker container? Also, I suspect I would need to "run" the docker container to allow ansible to connect to it.

like image 420
Andre Avatar asked Jul 14 '14 13:07

Andre


People also ask

Does Ansible work with Docker?

As mentioned, you can use Ansible to automate Docker and to build and deploy Docker containers. First, you'll need to have Docker SDK for Python installed.

How do I test an Ansible playbook on a virtual machine?

There are two ways of testing your playbook with a Vagrant vm. You can create and launch a vm and then apply the playbook with ansible-playbook command, specifying ip address of vm and required ssh certificate like any other remote machine. But there is a better way! We can use Vagrant's Ansible provisioning feature.


1 Answers

Running the playbook in a docker container may not actually be the best approach unless your stage and production servers are also Docker containers. The Docker ubuntu image is stripped down and will have some differences from a full installation. A better option might be to run the playbook in an Ubuntu VM that matches your staging and production installations.

That said, in order to run the ansible playbook within the container you should write a Dockerfile that runs your playbook. Here's a sample Dockerfile:

 # Start with the ubuntu image  FROM ubuntu  # Update apt cache  RUN apt-get -y update  # Install ansible dependencies  RUN apt-get install -y python-yaml python-jinja2 git  # Clone ansible repo (could also add the ansible PPA and do an apt-get install instead)  RUN git clone http://github.com/ansible/ansible.git /tmp/ansible   # Set variables for ansible  WORKDIR /tmp/ansible  ENV PATH /tmp/ansible/bin:/sbin:/usr/sbin:/usr/bin  ENV ANSIBLE_LIBRARY /tmp/ansible/library  ENV PYTHONPATH /tmp/ansible/lib:$PYTHON_PATH   # add playbooks to the image. This might be a git repo instead  ADD playbooks/ /etc/ansible/  ADD inventory /etc/ansible/hosts  WORKDIR /etc/ansible   # Run ansible using the site.yml playbook   RUN ansible-playbook /etc/ansible/site.yml -c local 

The ansible inventory file would look like

[local] localhost 

Then you can just docker build . (where . is the root of the directory where your playbooks and Dockerfile live), then docker run on the resulting image.

Michael DeHaan, the CTO of Ansible, has an informative blog post on this topic.

like image 63
Ben Whaley Avatar answered Sep 19 '22 15:09

Ben Whaley