How to Deploy Docker Containers with Ansible

In this blog post, we will cover how to deploy Docker containers with Ansible. Ansible is a powerful and simple configuration management tool that can be used in many different ways for managing your infrastructure and services. We’ll show you the steps needed to install Ansible on your machine, configure it to connect a Docker host (localhost) and deploy a container.

This post will go over all the processes to configure Ansible and the Docker module. Feel free to skip a step if you have already completed it.

Install Python 3.9

Let’s start and install Python 3.9 and VENV to run Ansible from. Using VENV allows us to isolate Ansible and make the environment more stable and shield it from changes.

sudo apt update && apt install python3.9  && apt-get install python3.9-dev python3.9-venv

Create Virtual ENV for Ansible

Once Python is installed, Let create a virtual environment for Ansible. The command below will create a new virtual environment running on Python 3.9.

python3.9 -m venv ~/virtualenv/ansible

Activate the Ansible VENV

Let’s go ahead and activate the Ansible environment and install Ansible.

source ~/virtualenv/ansible/bin/activate

Install Ansible

From the virtual environment, we install the latest version of Ansible using the command below.

sudo apt update  && sudo apt install software-properties-common  && sudo add-apt-repository --yes --update ppa:ansible/ansible  && sudo apt install ansible

Install Docker Module for Ansible

The most critical part of the post is to install the Docker module into the correct environment using pip3.9, as shown in the command below.

Important: If you installed Python3.9, you must use the same pip version to install the module. Otherwise, you will receive “ModuleNotFoundError: No module named ‘docker”

pip3.9 install docker

Set Localhost in Inventory file

Since my Docker host is running on localhost, I will set it in the inventory and set the python version as well.

localhost ansible_connection=local ansible_host= ansible_python_interpreter='~/virtualenv/ansible/bin/python3.9'

 Create Playbook

In the final step, I will deploy a container using the playbook below.

- hosts: localhost
    - name: Create a data container
        name: myansiblecontainer
        image: ubuntu
        state: absent

Run Playbook

To run the playbook, I’m using the command below.

ansible-playbook -i ~/hosts create_container.yaml  -vvv

To deactivate the Ansible virtual environment type.