In Module 7 you worked with containers without going looking for them: the aurora-ee execution environment is an image, AWX runs on Kubernetes and every job is a pod. Now Aurora Store is taking the step deliberately: the development team has written a new service, the catalog API, and wants to deliver it as a container image. Someone has to install Docker on a server, build and publish the image, start its containers with the right configuration and keep them that way over time. In this lesson you'll discover that Ansible doesn't compete with Docker but manages it: with the community.docker collection you'll install Docker Engine with a role of your own, build the API image, bring up its containers (first one by one and then with Docker Compose from a template), run Ansible inside containers and learn when something belongs in a Dockerfile and when in a playbook.

Contents

  1. Containers and Ansible: two tools that complement each other
  2. The new service: the catalog API on the api1 server
  3. The community.docker collection and its requirements
  4. A role to install Docker Engine: docker
  5. The API image: Dockerfile and community.docker.docker_image
  6. Containers one by one: docker_network and docker_container
  7. Docker Compose from Ansible: the aurora_catalog role
  8. Integrating it into Aurora: apiservers.yml and site.yml
  9. Ansible inside containers: the community.docker.docker connection
  10. Containers as test nodes
  11. Ansible versus Dockerfile: what goes where
  12. Best practices

  1. Containers and Ansible: two tools that complement each other

A container packages an application with all its dependencies into an immutable image. That solves the "it works on my machine" problem very well for the application, but it leaves many questions open that aren't about the application but about the infrastructure:

Question Does Docker answer it? Who answers it at Aurora?
What's inside the API image? Yes (Dockerfile) The development team
Which server has Docker installed, with which version and configuration? No Ansible (docker role)
Which containers run on each server, with which ports, volumes and variables? Partially (Compose) Ansible generates and applies the definition
How are each environment's secrets and data passed in? No Ansible (inventory, Vault)
How is the version upgraded in an orderly way across several servers? No Ansible (playbooks, AWX)
Is the server's operating system patched, with users and metrics? No Ansible (common role, node_exporter…)

The key idea of this lesson is the split of responsibilities:

  • Docker defines and runs the application: what runs.
  • Ansible prepares the servers and decides where, how and with which configuration it runs, declaratively, idempotently and versioned in aurora-infra, just as it already does with nginx or PostgreSQL.
flowchart LR
    DEV[Development team<br/>aurora-catalog repository] -->|Dockerfile| IMG[Image catalog:1.0.0]
    IMG -->|push| REG[(registry.aurora-store.example)]
    INFRA[aurora-infra<br/>docker and aurora_catalog roles] -->|Ansible| API1[api1: Docker Engine<br/>+ compose.yaml]
    REG -->|pull| API1

  1. The new service: the catalog API on the api1 server

2.1. What the service is

The catalog API (aurora-catalog) is a small HTTP service that publishes the store's products as JSON. For this lesson it's deliberately simple (it only uses the Python standard library), but it has what any real service has:

  • a port (8080) with two routes: /api/products (the catalog) and /health (service status, version and whether it can reach its cache);
  • data that comes from outside the image (the catalog file, which Ansible will manage);
  • a dependency: a Redis instance that will act as the API's cache (in this version the service only checks that it can reach it; actual use of the cache will come in later versions of the API).

2.2. Decision: a new server, api1

You could run the containers on web1 and web2, but mixing the static website with a container engine complicates both (firewall, memory, upgrades). Aurora creates a dedicated server:

Item Value
Name api1
IP 192.168.56.41
Memory / CPU 1536 MB / 1
Inventory group apiservers (child of aurora)
Service Catalog API + Redis, with Docker Compose

Add the machine to the MACHINES dictionary in lab/Vagrantfile, before awx1:

MACHINES = {
  "lb1"  => { ip: "192.168.56.10", memory: 512,  cpus: 1 },
  "web1" => { ip: "192.168.56.11", memory: 1024, cpus: 1 },
  "web2" => { ip: "192.168.56.12", memory: 1024, cpus: 1 },
  "db1"  => { ip: "192.168.56.21", memory: 2048, cpus: 2 },
  "api1" => { ip: "192.168.56.41", memory: 1536, cpus: 1 },
  "awx1" => { ip: "192.168.56.30", memory: 6144, cpus: 4 },
}

Create it, save its initial state and set up SSH access as you did with lb1 in Lesson 5.7:

cd ~/aurora-infra/lab
vagrant up api1
vagrant snapshot save api1 clean
cd ..

In ~/.ssh/config, add the alias and extend the line with the common options:

Host api1
    HostName 192.168.56.41

Host lb1 web1 web2 db1 api1 awx1 192.168.56.*
    User vagrant
    IdentityFile ~/.ssh/aurora_ed25519
    IdentitiesOnly yes

Accept its fingerprint (remember that host_key_checking = True):

ssh api1 hostname

2.3. The apiservers group in the inventory

In inventory/hosts.yml, add the group inside aurora, after dbservers:

        dbservers:               # Database servers (PostgreSQL)
          hosts:
            db1:
              ansible_host: 192.168.56.21
        apiservers:              # Containerized services (Docker)
          hosts:
            api1:
              ansible_host: 192.168.56.41

Since api1 is a member of aurora, common.yml and monitoring.yml already apply to it. Give it the baseline of any Aurora server before going on:

ansible-inventory --graph aurora
ansible-playbook site.yml --limit api1

The first command should show @apiservers with api1; the second applies users, common packages, motd, local facts and the metrics agent. The other playbooks have no hosts matching api1 and are skipped.

  1. The community.docker collection and its requirements

3.1. What it offers

community.docker is the community-maintained collection for managing Docker. Its most used pieces:

Content Type What it's for
docker_image Module Build, pull, tag, push or delete images
docker_image_build, docker_image_push, docker_image_pull Modules Specific variants (the build one uses buildx)
docker_container Module Create a container and keep it with its configuration
docker_network, docker_volume Modules Networks and volumes
docker_compose_v2 Module Apply a Docker Compose project (docker compose up/down)
docker_login Module Authenticate against a registry
docker_container_info, docker_host_info, docker_image_info Modules Queries (read-only)
community.docker.docker, community.docker.docker_api Connection Run Ansible inside a container (section 9)
community.docker.docker_containers Inventory Use containers as inventory hosts (Lesson 10.2)

3.2. Adding it to the project requirements

Like the rest of Aurora's collections, it's declared with an exact version in collections/requirements.yml (Lesson 7.3), after checking that its requires_ansible supports ansible-core 2.17 (the 4.x series of community.docker asks for >=2.15.0):

collections:
  # ufw and timezone. The 12 series is the latest compatible with ansible-core 2.17.
  - name: community.general
    version: "12.6.7"
  # PostgreSQL users, databases and checks.
  - name: community.postgresql
    version: "4.2.2"
  # timer, profile_tasks and profile_roles callbacks.
  - name: ansible.posix
    version: "2.2.2"
  # Docker Engine, images, containers and Compose (Lesson 8.1).
  - name: community.docker
    version: "4.7.0"

Install it in the project and check that you can see it:

ansible-galaxy collection install -r collections/requirements.yml
ansible-galaxy collection list community.docker
ansible-doc community.docker.docker_container | head -20

Remember that collections/requirements.yml is the single source of truth: AWX processes it when it syncs the project and aurora-ee uses it when it's built. The new version of the EE with this collection will be built by continuous integration in Lesson 8.3.

3.3. What the managed node needs

The Docker modules run on the server where Docker is (api1), not on your computer. There they need:

Requirement For which modules On api1 it's installed by
Docker Engine (API 1.25 or later) All docker role
Python requests library docker_container, docker_image, docker_network… docker role (python3-requests)
docker CLI with the compose plugin 2.18+ docker_compose_v2 docker role (docker-compose-plugin)
docker CLI with the buildx plugin docker_image_build docker role (docker-buildx-plugin)
Docker SDK for Python (docker) Only docker_swarm and docker_swarm_service Not needed at Aurora

Beware of old tutorials. For years, the recipe was "install the docker Python SDK on the managed node" (pip install docker or the python3-docker package). Old versions of the collection needed it for almost everything. Since the 3.x series, most modules ship their own Docker API client and only need requests; the SDK is left for the Swarm modules. If you see the error Failed to import the required Python library (requests), python3-requests is missing; don't install the SDK out of habit.

  1. A role to install Docker Engine: docker

4.1. Design

Following the criteria from Module 4, Aurora writes a generic role of its own, docker, that knows nothing about the store:

  • it installs Docker Engine from the official Docker repository (Ubuntu's docker.io package lags behind and doesn't ship the compose and buildx plugins in the version you need);
  • it manages /etc/docker/daemon.json with a template;
  • it gives access to Docker only to the users specified.
ansible-galaxy role init --init-path roles docker
rm -rf roles/docker/{files,tests,vars/main.yml}

(You keep defaults/, handlers/, meta/, tasks/, templates/ and vars/; you'll recreate the vars/main.yml file with your own content.)

4.2. Variables

roles/docker/defaults/main.yml:

---
# Docker Engine packages (official Docker repository).
docker_packages:
  - docker-ce
  - docker-ce-cli
  - containerd.io
  - docker-buildx-plugin
  - docker-compose-plugin

# Users with access to the Docker socket. Belonging to the docker group is equivalent to being root!
docker_users: []

# Registries allowed without TLS (labs only).
docker_insecure_registries: []

# Rotation of the containers' logs.
docker_log_max_size: 10m
docker_log_max_file: 3

# Keep containers running while the daemon restarts.
docker_live_restore: true

roles/docker/vars/main.yml (internal values that shouldn't be changed from the inventory):

---
docker_repo_url: https://download.docker.com/linux/ubuntu
docker_repo_key_url: https://download.docker.com/linux/ubuntu/gpg
docker_conflicting_packages:
  - docker.io
  - docker-compose
  - docker-compose-v2
  - podman-docker
  - containerd
  - runc
docker_daemon_config: /etc/docker/daemon.json

4.3. Tasks

roles/docker/tasks/main.yml:

---
- name: Docker packages
  tags: packages
  block:
    - name: Remove the distribution's Docker packages that conflict
      ansible.builtin.apt:
        name: "{{ docker_conflicting_packages }}"
        state: absent

    - name: Configure the official Docker repository
      ansible.builtin.deb822_repository:
        name: docker
        types: deb
        uris: "{{ docker_repo_url }}"
        suites: "{{ ansible_facts['distribution_release'] }}"
        components: stable
        architectures: "{{ 'arm64' if ansible_facts['architecture'] == 'aarch64' else 'amd64' }}"
        signed_by: "{{ docker_repo_key_url }}"
      register: docker_repo

    - name: Update the package cache if the repository has changed
      ansible.builtin.apt:
        update_cache: true
      when: docker_repo is changed

    - name: Install Docker Engine and its dependencies
      ansible.builtin.apt:
        name: "{{ docker_packages + ['python3-requests'] }}"
        state: present
        update_cache: true
        cache_valid_time: 3600

- name: Configure the Docker daemon
  ansible.builtin.template:
    src: daemon.json.j2
    dest: "{{ docker_daemon_config }}"
    owner: root
    group: root
    mode: "0644"
    validate: dockerd --validate --config-file %s
  notify: Restart Docker
  tags: config

- name: Ensure Docker is started and enabled
  ansible.builtin.systemd_service:
    name: docker
    state: started
    enabled: true
  tags: [packages, config]

- name: Give the specified users access to Docker
  ansible.builtin.user:
    name: "{{ item }}"
    groups: docker
    append: true
  loop: "{{ docker_users }}"
  tags: users

Points worth explaining:

  • ansible.builtin.deb822_repository writes /etc/apt/sources.list.d/docker.sources in APT's modern format (deb822). With signed_by pointing to a URL, the module downloads the key and embeds it in the file: you don't need apt-key (deprecated) or a separate step for the key.
  • The APT cache is updated explicitly when the repository changes. If you only used cache_valid_time: 3600, on a server whose cache is less than an hour old (for example, right after applying common) APT wouldn't yet know about the docker-ce packages and the installation would fail.
  • The distribution_release (noble) and architecture facts are part of the min subset that Aurora's playbooks have used since Lesson 5.8.
  • validate: dockerd --validate --config-file %s: Docker Engine checks the file before it's put in place; an incorrect daemon.json would prevent the daemon from starting.
  • The users tag on the last step adds to the functional tags strategy from Lesson 5.6.

4.4. Template and handler

roles/docker/templates/daemon.json.j2:

{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "{{ docker_log_max_size }}",
    "max-file": "{{ docker_log_max_file }}"
  },
  "live-restore": {{ docker_live_restore | to_json }},
  "insecure-registries": {{ docker_insecure_registries | to_json }}
}

Notice two details:

  • It doesn't carry the {{ ansible_managed }} header: JSON doesn't allow comments and the daemon wouldn't start. It's one of the few Aurora managed files without that mark (document it in the role's README).
  • The to_json filter turns Ansible values into valid JSON: true in lowercase and the list with double quotes. Writing {{ docker_insecure_registries }} without the filter would produce ['registry...'], with single quotes, which isn't JSON.

roles/docker/handlers/main.yml:

---
- name: Restart Docker
  ansible.builtin.systemd_service:
    name: docker
    state: restarted

With live-restore: true, restarting the daemon doesn't stop the running containers.

Complete meta/main.yml (author, license and platforms as in your other roles) and create meta/argument_specs.yml with the seven variables from defaults/ (you'll do it in Exercise 1).

4.5. Aurora's variables for the group

Create inventory/group_vars/apiservers.yml (for now with only the Docker part):

---
# Variables for the Aurora Store containerized service servers

# docker role parameters
# The lab registry (Lesson 7.6) has no TLS: acceptable only in the lab.
docker_insecure_registries:
  - registry.aurora-store.example:5000

4.6. First version of apiservers.yml

So that you can work with Docker for the rest of the lesson, create the group's playbook now, for the time being with only the container engine (you'll complete it in section 8):

---
- name: Configure the Aurora Store containerized service servers
  hosts: apiservers
  become: true
  gather_subset: [min]

  pre_tasks:
    - name: Resolve the lab internal names
      # Lab only: in the company these names are resolved by the internal DNS.
      ansible.builtin.lineinfile:
        path: /etc/hosts
        line: "192.168.56.30 git.aurora-store.example registry.aurora-store.example"
        regexp: '\sregistry\.aurora-store\.example(\s|$)'
      tags: always

  roles:
    - docker

The pre-task is needed because api1 will have to download code from Gitea and images from the registry, and those fictitious names only exist in the /etc/hosts files you configured in Lesson 7.2. Apply and check:

ansible-playbook apiservers.yml
ansible-playbook apiservers.yml          # second run: changed=0
ssh api1 'sudo docker version --format "{{.Server.Version}}" && sudo docker compose version'
ssh api1 'sudo docker info --format "{{.LoggingDriver}} {{.LiveRestoreEnabled}}"'

The last command should show json-file true: the daemon has read your daemon.json. (The double braces in --format belong to Go, not Jinja: here you type them in the terminal, not in a playbook.)

git add .
git commit -m "api1 server and docker role"

  1. The API image: Dockerfile and community.docker.docker_image

5.1. The application repository

The API code does not live in aurora-infra: it's an application with its own lifecycle, just as the nginx role has its own repository. The development team creates ~/aurora-catalog with two files. The first, app.py:

"""Aurora Store catalog API (teaching example: standard library only)."""
import json
import os
import socket
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

VERSION = os.environ.get("AURORA_CATALOG_VERSION", "unknown")
DATA = os.environ.get("AURORA_CATALOG_DATA", "/data/products.json")
REDIS_HOST = os.environ.get("AURORA_REDIS_HOST", "")
REDIS_PORT = int(os.environ.get("AURORA_REDIS_PORT", "6379"))


def redis_available():
    """Sends PING to Redis and expects +PONG (Redis RESP protocol)."""
    if not REDIS_HOST:
        return False
    try:
        with socket.create_connection((REDIS_HOST, REDIS_PORT), timeout=1) as connection:
            connection.sendall(b"PING\r\n")
            return connection.recv(16).startswith(b"+PONG")
    except OSError:
        return False


class Handler(BaseHTTPRequestHandler):
    def respond(self, code, body):
        payload = json.dumps(body, ensure_ascii=False).encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def do_GET(self):
        if self.path == "/health":
            self.respond(200, {"status": "ok", "version": VERSION, "redis": redis_available()})
        elif self.path == "/api/products":
            try:
                with open(DATA, encoding="utf-8") as file:
                    self.respond(200, json.load(file))
            except (OSError, ValueError) as error:
                self.respond(500, {"error": str(error)})
        else:
            self.respond(404, {"error": "not found"})


if __name__ == "__main__":
    ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()

You don't need to master Python to follow the lesson; what matters is its contract with the infrastructure: it reads its configuration from environment variables (AURORA_CATALOG_DATA, AURORA_REDIS_HOST…), reads the catalog from a file (which Ansible will put in place) on every request, listens on port 8080 and exposes /health so anyone can check whether it's healthy.

The second file, Dockerfile:

FROM docker.io/library/python:3.12-slim

ARG AURORA_CATALOG_VERSION=development
ENV AURORA_CATALOG_VERSION=${AURORA_CATALOG_VERSION} \
    PYTHONUNBUFFERED=1
LABEL org.opencontainers.image.title="aurora-catalog" \
      org.opencontainers.image.version="${AURORA_CATALOG_VERSION}"

RUN useradd --system --uid 10001 catalog
WORKDIR /app
COPY app.py .

USER 10001
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD python3 -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health', timeout=3)"
CMD ["python3", "app.py"]

Line by line: it starts from the official lightweight Python 3.12 image; it receives the version as a build argument (ARG) and keeps it as an environment variable; it adds standard OCI labels; it creates an unprivileged user and runs the application as that user (never as root); it declares the port and a health check that Docker will run periodically.

Version the repository and publish it on Gitea, in the ops organization, as public (free read access on the internal network, just like ansible-role-nginx in Lesson 7.4):

cd ~/aurora-catalog
git init -b main
git add app.py Dockerfile
git commit -m "Catalog API 1.0.0"
git tag -a 1.0.0 -m "Version 1.0.0"
# First create the empty ops/aurora-catalog repository on Gitea (public)
git remote add origin http://git.aurora-store.example/ops/aurora-catalog.git
git push -u origin main --tags
cd ~/aurora-infra

5.2. Building and publishing with Ansible

Where is the image built? You need a Docker Engine, and api1 will already have one. In this lesson api1 will also act as the build machine (in Lesson 8.3 you'll see that the natural thing is for the application repository's continuous integration to build it).

Add to inventory/group_vars/apiservers.yml:

# Catalog API image and version
aurora_catalog_image: registry.aurora-store.example:5000/aurora/catalog
aurora_catalog_version: "1.0.0"
aurora_catalog_source: http://git.aurora-store.example/ops/aurora-catalog.git

And create the catalog-image.yml playbook at the root:

---
# Builds the catalog API image and pushes it to the lab registry.
# Usage: ansible-playbook catalog-image.yml [-e aurora_catalog_version=X.Y.Z]
- name: Build the Aurora Store catalog API image
  hosts: apiservers[0]
  become: true
  gather_facts: false

  tasks:
    - name: Install git to download the code
      ansible.builtin.apt:
        name: git
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Download the code of the specified version
      ansible.builtin.git:
        repo: "{{ aurora_catalog_source }}"
        dest: /opt/build/aurora-catalog
        version: "{{ aurora_catalog_version }}"
        force: true

    - name: Build and push the image
      community.docker.docker_image:
        name: "{{ aurora_catalog_image }}"
        tag: "{{ aurora_catalog_version }}"
        source: build
        build:
          path: /opt/build/aurora-catalog
          pull: true
          args:
            AURORA_CATALOG_VERSION: "{{ aurora_catalog_version }}"
        push: true

Explanation:

  • hosts: apiservers[0]: the first host in the group; even if there were several servers, the image is built only once.
  • ansible.builtin.git with version: "1.0.0" checks out exactly that tag: you build what's versioned, not what's on somebody's laptop.
  • community.docker.docker_image with source: build builds from build.path; build.pull: true pulls the latest version of the base image (python:3.12-slim) to pick up patches; build.args fills in the ARG in the Dockerfile; push: true uploads it to the registry given in the name itself.
  • Idempotency: if the catalog:1.0.0 image already exists on api1, the module does not rebuild it (changed=false). That's correct: a published tag isn't reused (the same thing you decided with aurora-ee). To force a rebuild there's force_source: true, but for a new version the right thing is a new tag.

Run the playbook and query the registry:

ansible-playbook catalog-image.yml
curl -s http://registry.aurora-store.example:5000/v2/aurora/catalog/tags/list
{"name":"aurora/catalog","tags":["1.0.0"]}

If your registry required a username and password, you'd first add a community.docker.docker_login task with registry_url, username and password (from Vault and with no_log: true). The lab registry has neither authentication nor TLS; in production it must have both (Lesson 9.2).

  1. Containers one by one: docker_network and docker_container

Before packaging everything with Compose, it's worth seeing how Ansible manages each piece. This demo playbook, demo-containers.yml (you'll delete it at the end of the section), brings up the API and its Redis with the basic modules:

---
- name: Demonstration of standalone containers on api1
  hosts: api1
  become: true
  gather_facts: false

  tasks:
    - name: Create the demo private network
      community.docker.docker_network:
        name: aurora-demo
        driver: bridge

    - name: Start Redis
      community.docker.docker_container:
        name: demo-redis
        image: docker.io/library/redis:7.4-alpine
        networks:
          - name: aurora-demo
        volumes:
          - demo-redis-data:/data
        restart_policy: unless-stopped
        healthcheck:
          test: ["CMD", "redis-cli", "ping"]
          interval: 10s
          timeout: 3s
          retries: 3
        state: healthy

    - name: Create the API data directory
      ansible.builtin.file:
        path: /opt/demo-catalog
        state: directory
        mode: "0755"

    - name: Publish a minimal catalog
      ansible.builtin.copy:
        content: '[{"sku": "CAF-DEMO-250", "name": "Test coffee", "price": 9.9}]'
        dest: /opt/demo-catalog/products.json
        mode: "0644"

    - name: Start the catalog API
      community.docker.docker_container:
        name: demo-catalog
        image: "{{ aurora_catalog_image }}:{{ aurora_catalog_version }}"
        networks:
          - name: aurora-demo
        published_ports:
          - "8080:8080"
        env:
          AURORA_REDIS_HOST: demo-redis
          AURORA_CATALOG_DATA: /data/products.json
        volumes:
          - /opt/demo-catalog:/data:ro
        restart_policy: unless-stopped
        state: healthy
        healthy_wait_timeout: 60

Parameter by parameter:

Parameter Equivalent in docker run Comment
name --name Identifies the container: it's the key to idempotency
image The image With an explicit tag; never latest
networks --network On a network of their own, containers find each other by name (demo-redis)
published_ports -p 8080:8080 host_port:container_port
env -e Values must be strings: quote numbers and booleans
volumes -v Named volume (demo-redis-data:/data) or host directory (/opt/...:/data:ro)
restart_policy --restart no, on-failure, always, unless-stopped
healthcheck --health-* Replaces or defines the health check
state — present, started, stopped, absent and healthy

The healthy state deserves attention: the module isn't satisfied with the container being started; it waits for its health check to report healthy (for up to healthy_wait_timeout seconds). For Redis it uses the play's healthcheck; for the API, the HEALTHCHECK you defined in the Dockerfile. That way, the API task doesn't start until Redis responds.

Run it twice and test:

ansible-playbook demo-containers.yml
ansible-playbook demo-containers.yml      # second run: changed=0
curl -s http://192.168.56.41:8080/health
{"status": "ok", "version": "1.0.0", "redis": true}

6.1. Idempotency of docker_container

docker_container compares the configuration you ask for with that of the existing container. If they match, it does nothing; if not, it recreates the container (containers are immutable: they aren't "edited"). Check it: in the last task, add AURORA_REDIS_PORT: "6379" to env and run first in check mode and then for real:

ansible-playbook demo-containers.yml --check --diff
ansible-playbook demo-containers.yml
ssh api1 'sudo docker ps --format "{{.Names}} {{.Status}}"'

Check mode shows the difference in env without touching anything; the real run returns changed on the API task and docker ps shows that demo-catalog has only been up for a few seconds (it's a new container), while demo-redis is still as it was. Two practical consequences:

  • What you don't declare is decided by Docker; what you declare, Ansible maintains. If someone runs docker run by hand with the same name and a different configuration, the next run corrects it (drift).
  • Recreating a container means a brief outage. For services with several replicas you'd combine it with serial (Lesson 5.7).

Finally, query the state without changing anything and clean up the demo:

    - name: Query the API container
      community.docker.docker_container_info:
        name: demo-catalog
      register: demo_info

    - name: Show its health status
      ansible.builtin.debug:
        msg: "{{ demo_info.container.State.Health.Status }}"
ssh api1 'sudo docker rm -f demo-catalog demo-redis && sudo docker network rm aurora-demo && sudo docker volume rm demo-redis-data && sudo rm -rf /opt/demo-catalog'
rm demo-containers.yml

(The proper Ansible way would be a play with state: absent on each resource; here you use docker directly to quickly clean up a demo.)

  1. Docker Compose from Ansible: the aurora_catalog role

7.1. Why Compose

With standalone containers, the service definition ends up spread across several tasks and you control the order. Docker Compose describes all of an application's containers, networks and volumes in a single compose.yaml file, and anyone on the team can inspect it with docker compose ps or docker compose logs. The combination Aurora adopts:

  • Ansible generates compose.yaml from a Jinja2 template: the values (version, ports, names) come from the inventory.
  • community.docker.docker_compose_v2 applies it (docker compose up) idempotently.

7.2. The role

ansible-galaxy role init --init-path roles aurora_catalog
rm -rf roles/aurora_catalog/{files,handlers,tests,vars}

roles/aurora_catalog/defaults/main.yml:

---
aurora_catalog_version: "1.0.0"
aurora_catalog_dir: /opt/aurora-catalog
aurora_catalog_port: 8080
aurora_catalog_redis_image: docker.io/library/redis:7.4-alpine
aurora_catalog_products: []

aurora_catalog_image has no default value: it's mandatory (declare it with required: true in meta/argument_specs.yml, like aurora_app_db_host in Lesson 4.6). In meta/main.yml, the dependency on the container engine, just as aurora_app depends on nginx:

dependencies:
  - role: docker

roles/aurora_catalog/templates/compose.yaml.j2:

# {{ ansible_managed }}
name: aurora-catalog

services:
  catalog:
    image: "{{ aurora_catalog_image }}:{{ aurora_catalog_version }}"
    restart: unless-stopped
    ports:
      - "{{ aurora_catalog_port }}:8080"
    environment:
      AURORA_REDIS_HOST: redis
      AURORA_CATALOG_DATA: /data/products.json
    volumes:
      - ./data:/data:ro
    depends_on:
      redis:
        condition: service_healthy
    networks:
      - aurora-catalog
    # The health check comes from the image's HEALTHCHECK.

  redis:
    image: "{{ aurora_catalog_redis_image }}"
    restart: unless-stopped
    volumes:
      - redis-data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 3s
      retries: 3
    networks:
      - aurora-catalog

networks:
  aurora-catalog: {}

volumes:
  redis-data: {}

roles/aurora_catalog/templates/products.json.j2 (JSON again, no header):

{{ aurora_catalog_products | to_nice_json(indent=2) }}

roles/aurora_catalog/tasks/main.yml:

---
- name: Create the service directories
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    owner: root
    group: root
    mode: "0755"
  loop:
    - "{{ aurora_catalog_dir }}"
    - "{{ aurora_catalog_dir }}/data"
  tags: [deploy, config]

- name: Publish the product catalog
  ansible.builtin.template:
    src: products.json.j2
    dest: "{{ aurora_catalog_dir }}/data/products.json"
    owner: root
    group: root
    mode: "0644"
  tags: [deploy, config]

- name: Publish the Docker Compose definition
  ansible.builtin.template:
    src: compose.yaml.j2
    dest: "{{ aurora_catalog_dir }}/compose.yaml"
    owner: root
    group: root
    mode: "0644"
  tags: [deploy, config]

- name: Deploy the service with Docker Compose
  community.docker.docker_compose_v2:
    project_src: "{{ aurora_catalog_dir }}"
    state: present
    pull: missing
    remove_orphans: true
    wait: true
    wait_timeout: 120
  tags: [deploy, config]

Decisions worth understanding:

  • The data/ directory is mounted, not the file. The template module writes a new file and renames it over the old one (atomic write). If you mounted the file on its own (./data/products.json:/data/products.json), the container would keep seeing the old file (the mount points to the original inode). By mounting the directory, the API always sees the current version, without a restart.
  • pull: missing: pulls the images only if they aren't there. Since tags are immutable, there's no need to ask the registry on every run.
  • remove_orphans: true: if one day you remove a service from the template, its container is deleted.
  • wait: true: equivalent to docker compose up --wait; the task doesn't finish until the services are running and healthy (or it fails when wait_timeout is exceeded).
  • Idempotency: if compose.yaml and the images don't change, docker compose up doesn't recreate anything and the module returns changed=false. When aurora_catalog_version changes, the template changes and Compose recreates only the catalog service; Redis and its volume stay intact.
  • There's no restart handler: it's docker compose up that decides what to recreate by comparing the definition with what's running.

7.3. Aurora's data

Complete inventory/group_vars/apiservers.yml:

# aurora_catalog role parameters (the image and version are further up)
aurora_catalog_port: 8080
aurora_catalog_products:
  - sku: CAF-ETI-250
    name: "Ethiopia Yirgacheffe 250 g"
    price: 12.50
  - sku: CAF-COL-250
    name: "Colombia Huila 250 g"
    price: 11.00
  - sku: CAF-GUA-1000
    name: "Guatemala Antigua 1 kg"
    price: 38.00

  1. Integrating it into Aurora: apiservers.yml and site.yml

Complete apiservers.yml (section 4.6) with the new role and the final checks, in the same shape as the other playbooks:

---
- name: Configure the Aurora Store containerized service servers
  hosts: apiservers
  become: true
  gather_subset: [min]

  pre_tasks:
    - name: Resolve the lab internal names
      # Lab only: in the company these names are resolved by the internal DNS.
      ansible.builtin.lineinfile:
        path: /etc/hosts
        line: "192.168.56.30 git.aurora-store.example registry.aurora-store.example"
        regexp: '\sregistry\.aurora-store\.example(\s|$)'
      tags: always

  roles:
    - docker
    - aurora_catalog

  post_tasks:
    - name: Wait for the catalog API to respond
      ansible.builtin.uri:
        url: "http://localhost:{{ aurora_catalog_port }}/health"
        return_content: true
      register: aurora_catalog_check
      until: aurora_catalog_check.status == 200
      retries: 10
      delay: 3
      check_mode: false
      tags: always

    - name: Check that the API serves the deployed version and reaches Redis
      ansible.builtin.assert:
        that:
          - aurora_catalog_check.json.version == aurora_catalog_version
          - aurora_catalog_check.json.redis
        fail_msg: "Unexpected API response: {{ aurora_catalog_check.json | default('no JSON') }}"
        quiet: true
      tags: always

As in webservers.yml, the docker role appears explicitly even though aurora_catalog depends on it (deduplication prevents it from running twice). uri automatically parses the JSON response into aurora_catalog_check.json.

Add the new playbook to site.yml, before the metrics agent, and update the header:

#   webservers.yml     web servers, one at a time         -> nginx and aurora_app roles + checks
#   apiservers.yml     containerized services             -> docker and aurora_catalog roles + checks
#   monitoring.yml     all servers (aurora group)         -> geerlingguy.node_exporter role (community)
- name: Web servers
  ansible.builtin.import_playbook: webservers.yml

- name: Containerized services
  ansible.builtin.import_playbook: apiservers.yml

- name: Metrics agent
  ansible.builtin.import_playbook: monitoring.yml

The catalog:1.0.0 image is already in the registry (section 5.2). Apply and check:

ansible-playbook site.yml --limit api1 --check --diff   # what's going to change?
ansible-playbook site.yml --limit api1                  # API + Redis running
ansible-playbook site.yml --limit api1                  # idempotency: changed=0
curl -s http://192.168.56.41:8080/api/products
ssh api1 'sudo docker compose -f /opt/aurora-catalog/compose.yaml ps'

docker compose ps shows the aurora-catalog-catalog-1 and aurora-catalog-redis-1 containers (project, service and replica number), both healthy. Notice that the deployment depends on an artifact (the image) produced in another process (catalog-image.yml): if someone bumps aurora_catalog_version without having published the image, the deployment will fail when pulling it. In Lesson 8.3 you'll organize that flow into a pipeline.

Docker and the firewall. Docker publishes ports by manipulating iptables directly, ahead of the ufw rules. A port published with ports: is reachable even if ufw doesn't allow it. If a service should only listen locally, publish it as "127.0.0.1:8080:8080". You'll review this in Lesson 9.2.

Make a commit:

git add .
git commit -m "Catalog API 1.0.0 on api1: image, aurora_catalog role with Compose and apiservers.yml in site.yml"
git push

  1. Ansible inside containers: the community.docker.docker connection

So far Ansible has managed Docker from the outside (SSH to api1 and modules that talk to the daemon). It can also work inside a container, as if it were just another host, thanks to the collection's connection plugins:

Connection How it gets into the container Requirements on your computer
community.docker.docker Runs the docker exec / docker cp CLI docker CLI
community.docker.docker_api Talks directly to the Docker API requests library
ansible.builtin.ssh (the usual one) SSH into the container An SSH server in the container (not recommended)

The container needs Python for most modules (the python:* images have it; ubuntu:24.04 doesn't, and you'd install it with ansible.builtin.raw).

The connection runs on your control node: it launches docker exec against whichever daemon the CLI points to. In the lab, the daemon is on api1, and the Docker CLI knows how to talk to a remote daemon over SSH (-H ssh://user@host). You need:

  1. The Docker client on your computer (the docker-ce-cli package from Docker's repository or the one your system ships; you don't need the local daemon).
  2. The SSH user (vagrant) to be able to use Docker on api1 without sudo. Add to inventory/group_vars/apiservers.yml:
# Lab only: vagrant uses Docker without sudo (docker connection from Lesson 8.1).
# Belonging to the docker group is equivalent to being root on api1 (reviewed in Lesson 9.2).
docker_users:
  - vagrant

and apply with ansible-playbook apiservers.yml --tags users.

Now, a test inventory, tests/containers.yml (it's a demo: you'll delete it):

---
containers:
  hosts:
    aurora-catalog-catalog-1:      # name Compose gave to the API container
  vars:
    ansible_connection: community.docker.docker
    ansible_docker_extra_args: "-H ssh://vagrant@api1"
    ansible_python_interpreter: /usr/local/bin/python3
  • The host name is the container name (or ansible_host if you want an alias).
  • ansible_docker_extra_args adds options to every docker call: here, using the remote daemon.
  • ansible_python_interpreter: the official image's Python is in /usr/local/bin.
ansible -i tests/containers.yml containers -m ansible.builtin.ping
ansible -i tests/containers.yml containers -m ansible.builtin.command -a "whoami"
ansible -i tests/containers.yml containers -m ansible.builtin.setup -a "filter=ansible_distribution*"

whoami returns catalog: Ansible gets in with the image's user. This is useful for inspecting and troubleshooting (reading files, checking environment variables), but modifying a running container is an anti-pattern: the change is lost when it's recreated. If something has to change, you change the image or the definition.

  1. Containers as test nodes

Where the Docker connection shines is in testing: an Ubuntu 24.04 container takes a second to start and is destroyed without a trace, much faster than a Vagrant VM. Try applying Aurora's common packages in a throwaway one:

ssh api1 'docker run -d --name test-ubuntu docker.io/library/ubuntu:24.04 sleep infinity'

Add the host to the test inventory:

tests:
  hosts:
    test-ubuntu:
  vars:
    ansible_connection: community.docker.docker
    ansible_docker_extra_args: "-H ssh://vagrant@api1"

And a tests/test-common.yml playbook:

---
- name: Test the common role in a throwaway container
  hosts: tests
  gather_facts: false

  pre_tasks:
    - name: Install Python in the container (the image doesn't include it)
      ansible.builtin.raw: test -e /usr/bin/python3 || (apt-get update && apt-get install -y python3)
      changed_when: false

    - name: Gather the minimal facts
      ansible.builtin.setup:
        gather_subset: [min]

  roles:
    - common
ansible-playbook -i tests/containers.yml tests/test-common.yml --tags packages
ssh api1 'docker rm -f test-ubuntu'
rm -r tests/

Notice several details:

  • raw doesn't need Python: it's the classic way to "prepare" an empty host.
  • You only apply --tags packages: a container is not a VM. It doesn't have systemd, so tasks such as setting the time zone with timedatectl or starting services wouldn't work the same way. To test complete roles, images prepared with systemd or VMs are used.
  • The -i option replaces the inventory from ansible.cfg, so the variables in inventory/group_vars/ aren't loaded here: the role uses its default values (common_packages: [curl, vim]). It's a good reminder that a test should declare its own data and not depend on the production inventory.

This technique, organized and automated (create containers, apply the role, check idempotency, verify and destroy), is exactly what Molecule does, which you'll study in Lesson 9.5.

  1. Ansible versus Dockerfile: what goes where

The most frequent question when putting the two tools together is "do I install this in the Dockerfile or with Ansible?". The general rule: what's part of the application goes in the image; what depends on the environment or the server goes in Ansible.

Item Dockerfile (image) Ansible
Application dependencies (Python, libraries) ✔
Application code ✔
Unprivileged user, port, HEALTHCHECK ✔
Installing and configuring Docker on the server ✔
Per-environment data and configuration (catalog, URLs, published ports) ✔ (templates, environment variables)
Secrets ✔ (Vault → environment variables or mounted files; never in the image)
Which version runs on which server ✔ (inventory)
Server operating system (patches, users, metrics) ✔

And what about using Ansible to build the image, running a playbook inside the Dockerfile (or with tools such as ansible-bender)? It's possible, but it's rarely worth it:

  • The layers of a Dockerfile are cached; a playbook is a single, opaque and slower layer.
  • The image should be small and simple; a role designed for servers (users, systemd, firewall) drags along things a container doesn't need.
  • It makes sense when you already have complex software installation roles and want to reuse them as they are, or for "full machine" images (for example, company base images).

At Aurora, the API image is defined by its Dockerfile and Ansible takes care of the server and the deployment.

  1. Best practices

  • Immutable, explicit tags: catalog:1.0.0, never latest. Each service's version lives in the inventory and in Git.
  • A registry with TLS and authentication in production; insecure-registries only in the lab.
  • Secrets outside the image: they're injected at deployment time with variables encrypted with Vault and no_log: true.
  • Persistent data in named volumes (redis-data), never inside the container.
  • Health checks in the image or in Compose, and wait/state: healthy in Ansible so the deployment fails if the service doesn't start.
  • Log rotation configured in the daemon (daemon.json), or the containers' JSON files will end up filling the disk.
  • Be careful with the docker group (equivalent to root) and with published ports (they bypass ufw).
  • Don't modify running containers with Ansible: change the image or the definition and recreate them.
  • Compose generated from a template and applied with docker_compose_v2 for single-server services; for several servers with high availability, an orchestrator (Lesson 8.2).

Common Mistakes and Tips

  • Failed to import the required Python library (requests): python3-requests is missing on the managed node (not on your computer). It's not the Docker SDK that's missing.
  • Error connecting: ... Permission denied on the socket: the task runs without become and the user isn't in the docker group. At Aurora, plays use become: true.
  • http: server gave HTTP response to HTTPS client when pushing or pulling: the registry has no TLS and the daemon doesn't have it in insecure-registries (or the daemon hasn't been restarted after changing daemon.json).
  • The container is recreated on every run: some value doesn't match what Docker returns (typically: unquoted numbers in env, or an untagged image that resolves to another one). Run with --diff to see what differs.
  • Quotes in restart_policy: no: without quotes, YAML interprets it as the boolean false; write restart_policy: "no".
  • The container keeps seeing the old file: you mounted a standalone file that Ansible replaces; mount its directory.
  • docker_compose_v2 fails with "Docker CLI ... compose plugin": docker-compose-plugin is missing; the old docker-compose (v1, in Python) is no longer supported by the module.
  • Tip: ssh api1 'sudo docker compose -f /opt/aurora-catalog/compose.yaml logs --tail 20' is your first troubleshooting tool when wait times out.

Exercises

Exercise 1: argument_specs for the docker role

Write roles/docker/meta/argument_specs.yml for the seven variables in defaults/main.yml, with their types, short descriptions and documented default values. Add the constraint that docker_log_max_file must be an integer.

Exercise 2: version 1.1.0 of the API

The development team releases version 1.1.0 of aurora-catalog (a new tag in Git). Write the sequence of commands to build the image and deploy it on api1, and explain which containers are recreated and why Redis doesn't lose its data.

Exercise 3: Redis only locally

By mistake, someone adds ports: ["6379:6379"] to the redis service in the template. What risk does this pose, even if ufw were active on api1? Does the API need it to talk to Redis? Propose the fix.

Solutions

Exercise 1.

---
argument_specs:
  main:
    short_description: Installs Docker Engine from the official Docker repository
    author: Alex Admin (Aurora Store)
    options:
      docker_packages:
        type: list
        elements: str
        description: Docker Engine packages to install.
        default: [docker-ce, docker-ce-cli, containerd.io, docker-buildx-plugin, docker-compose-plugin]
      docker_users:
        type: list
        elements: str
        description: Users added to the docker group (equivalent to root).
        default: []
      docker_insecure_registries:
        type: list
        elements: str
        description: Registries allowed without TLS. Labs only.
        default: []
      docker_log_max_size:
        type: str
        description: Maximum size of each container log file.
        default: 10m
      docker_log_max_file:
        type: int
        description: Number of log files kept per container.
        default: 3
      docker_live_restore:
        type: bool
        description: Keep containers running when the daemon restarts.
        default: true

Remember (Lesson 4.6) that default in argument_specs only documents; the actual value still lives in defaults/main.yml. With type: int, -e docker_log_max_file=three will fail validation before the first task.

Exercise 2.

# In inventory/group_vars/apiservers.yml: aurora_catalog_version: "1.1.0"
ansible-playbook catalog-image.yml
ansible-playbook apiservers.yml --tags deploy
curl -s http://192.168.56.41:8080/health      # "version": "1.1.0"
git commit -am "Catalog API 1.1.0" && git push

Only the image: line of the catalog service in compose.yaml changes, so docker compose up recreates only that container. Redis doesn't change (same image and configuration) and its data lives in the named volume redis-data, which survives even if its container is recreated. Notice that the always tag keeps the version check even when you use --tags deploy.

Exercise 3. Docker publishes the port by inserting iptables rules ahead of ufw's, so Redis (without a password) would be reachable from the whole network: anyone could read or wipe the cache, or abuse administrative commands. The API does not need it: both containers are on the aurora-catalog network and the API reaches Redis by its service name (redis:6379). The fix is to remove ports: from the redis service; if an administrator needed access from the server itself, it would be published as "127.0.0.1:6379:6379", or better, with docker compose exec redis redis-cli.

Conclusion

You've seen that Ansible and Docker split the work: the image defines what runs and Ansible decides where and how. With the community.docker collection (which in its current versions needs requests on the managed node, not the Docker SDK) you've created the generic docker role, which installs Docker Engine from the official repository with deb822_repository and manages daemon.json; you've built and published the catalog API image with docker_image; you've handled networks and containers one by one with docker_network and docker_container (and its healthy state); and you've adopted for Aurora the compose.yaml template + docker_compose_v2 pattern in the aurora_catalog role, deployed on the new api1 server with apiservers.yml inside site.yml. You've also run Ansible inside containers with the community.docker.docker connection and used them as throwaway test nodes, the seed of Molecule. But the catalog API runs on a single server: if api1 goes down, there's no catalog, and scaling it would mean distributing containers by hand. In the next lesson, Ansible and Kubernetes, you'll deploy that same image on a Kubernetes cluster with the kubernetes.core collection, where replicas, restarts and rolling updates are the orchestrator's responsibility.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved