Maab S.
5min Read

How To Use Ansible to Deploy Docker Containers on Debian 11

Use Ansible deploy Docker containers on Debian 11

The only efficient way to manage and configure modern application environments is via automation. Ansible is an automation tool that uses YAML scripts to configure servers, install prerequisites, deploy applications, and orchestrate even complicated IT processes, like rolling upgrades and continuous deployments.

In the following article, we’ll install Ansible on a Debian 11 machine, and then create an Ansible playbook to install and run Docker containers. Let’s begin!


How to use Ansible

At the heart of all Ansible configurations are playbooks. An Ansible playbook is a collection of YAML scripts, which declare configurations, and define a set of steps to be executed, on one or more machines, in a certain order.

A playbook defines execution plans/processes via plays. Each play executes a task, which contributes to the overall goal of the playbook. For example, if we create a playbook for the installation of a web server, we can define different plays to:

  1. Install the latest version of the web server.
  2. Install the latest version of the database.
  3. Fetch application code from the GIT repository, and put it in the right place.
  4. Run any pre-flight checks.
  5. Start the web server.

1. Install Ansible

Let’s get started by installing Ansible on our Debian 11 machine. Follow these steps:

  1. Install the prerequisites:
    sudo apt-get install gnupg2 curl
  2. As the Ansible package is not available in the default repository, we’ll have to add the Ansible repository to fetch and install it. Add the following line to your /etc/apt/sources.list file:
    deb http://ppa.launchpad.net/ansible/ansible/ubuntu focal main
  3. Now, add the GPG key:
    apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 93C4A3FD7BB9C367
  4. Run update to fetch the latest list of available packages:
    sudo apt-get update
  5. Now we’re ready to install the Ansible package:
    sudo apt-get install ansible
  6. To verify the installation, use the following command:
    ansible --version
  7. You should get an output like this:
    ansible [core 2.12.2]
    config file = /etc/ansible/ansible.cfg
    configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
    ansible python module location = /usr/lib/python3/dist-packages/ansible
    ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
    executable location = /usr/bin/ansible
    python version = 3.9.2 (default, Feb 28 2021, 17:03:44) [GCC 10.2.1 20210110]
    jinja version = 2.11.3
    libyaml = True

2. Create an Ansible playbook

Now that we’ve installed Ansible on our system, we’re ready to create our first playbook. Follow these steps:

  1. Make a new directory for the playbook files:
    mkdir ansible
    mkdir ansible/vars
  2. Create a new file named default.yml in the ansible/vars sub-directory, and add the following lines to it:
    ---
    no_containers: 3
    container_name: test
    container_image: debian
    command_to_run: sleep 1h
  3. We will be referencing the above variables in our playbook:
    • The no_containers will be the number of containers we create,
    • container_name indicates the name of the containers,
    • container_image specifies the image to use for the containers, and
    • command_to_run is the command we will be running on the containers.
    • Since this just an exercise, we will be asking our containers to simply sleep for 1 hour, and do nothing.
  4. Create a new file named playbook.yml inside the ansible directory, and add the following lines to it:
    ---
    - hosts: localhost
      become: true
      vars_files:
        - vars/default.yml
    
      tasks:
        - name: Install pre-reqs for Docker and Ansible
          apt: name={{ item }} state=latest update_cache=yes
          loop: [ 'apt-transport-https', 'ca-certificates', 'curl', 'software-properties-common', 'python3-pip', 'virtualenv', 'python3-setuptools']
    
        - name: Add the GPG key for Docker
          shell: 'curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg'
    
        - name: Add the repository to fetch the docker package
          shell: 'echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian bullseye stable" | tee /etc/apt/sources.list.d/docker.list'
    
        - name: Update source list and then install docker
          apt: update_cache=yes name=docker-ce state=latest
    
        - name: Install the Docker module for Python, required by ansible
          pip:
            name: docker
    
        - name: Pull the official Debian image using the container_image variable. This image will be used in next step.
          docker_image:
            name: "{{ container_image }}"
            source: pull
    
        - name: Creates 3 containers, using the variables we defined in the vars file
          docker_container:
            name: "{{ container_name }}{{ item }}"
            image: "{{ container_image }}"
            command: "{{ command_to_run }}"
            state: present
          with_sequence: count={{ no_containers }}
  5. The above file is our entire playbook to:
    • install Docker,
    • pull the Debian image from Docker Hub,
    • and then run three containers, using the variables defined in the ansible/vars file.
  6. All the name identifiers in the file indicate the purpose of various tasks.

3. Run the Ansible playbook

At this point, we’re ready to run our playbook, and have it install Docker.

Execute the following command:

ansible-playbook playbook.yml -l localhost -u username

For a successful execution of the playbook, you should get an output similar to the following:

PLAY [localhost] ************************************************************************************************************************************************************************************************************
TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************ok: [localhost]

TASK [Install pre-reqs for Docker and Ansible] ******************************************************************************************************************************************************************************ok: [localhost] => (item=apt-transport-https)
ok: [localhost] => (item=ca-certificates)
ok: [localhost] => (item=curl)
ok: [localhost] => (item=software-properties-common)
changed: [localhost] => (item=python3-pip)
changed: [localhost] => (item=virtualenv)
ok: [localhost] => (item=python3-setuptools)

TASK [Add the GPG key for Docker] *******************************************************************************************************************************************************************************************changed: [localhost]

TASK [Add the repository to fetch the docker package] ***********************************************************************************************************************************************************************changed: [localhost]

TASK [Update source list and then install docker] ***************************************************************************************************************************************************************************ok: [localhost]

TASK [Install the Docker module for Python, required by ansible] ************************************************************************************************************************************************************changed: [localhost]

TASK [Pull the official Debian image using the container_image variable. This image will be used in next step.] *************************************************************************************************************changed: [localhost]

TASK [Creates 3 containers, using the variables we defined in the vars file] ************************************************************************************************************************************************changed: [localhost] => (item=1)
changed: [localhost] => (item=2)
changed: [localhost] => (item=3)

PLAY RECAP ******************************************************************************************************************************************************************************************************************localhost                  : ok=8    changed=6    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Use the following command to verify that 3 new containers were indeed spawned:

docker container ls –a

The following output should appear:

CONTAINER ID   IMAGE     COMMAND      CREATED         STATUS    PORTS     NAMES
de396ecc826e   debian    "sleep 1h"   2 minutes ago   Created             test3
db93b9a007bd   debian    "sleep 1h"   2 minutes ago   Created             test2
94a5379ef49a   debian    "sleep 1h"   2 minutes ago   Created             test1

That sums up this guide to set up Docker containers using an Ansible playbook.

To learn more, you may refer to the extensive documentation, available on the official Ansible website.


The Author

Maab S.

Maab is an experienced software engineer who specializes in explaining technical topics to a wider audience.

More posts from Maab