This tutorial guides you through installing Docker on multiple hosts using Ansible and the popular community-maintained Ansible role geerlingguy.docker.


Prerequisites

Before starting, ensure you have:


Step 1: Create the Ansible Playbook

Create a file named docker-playbook.yml:

- name: Install Docker using geerlingguy.docker role
  hosts: all
  become: yes  # Use sudo to elevate privileges
  gather_facts: yes

  roles:
    - geerlingguy.docker

This simple playbook applies the Docker installation role to all specified hosts.


Step 2: Define Role and Collection Dependencies

Create a file named requirements.yml to clearly define the external Ansible role and collection dependencies:

roles:
  - name: geerlingguy.docker
    version: 7.4.1  # Specify version for consistency

collections:
  - name: community.docker
    version: ">=3.0.0"

Specifying versions ensures repeatable, consistent deployments.


Step 3: Install Required Roles and Collections

Run the following command to install the dependencies specified in requirements.yml:

ansible-galaxy install -r requirements.yml

This command fetches and installs both the role and the collection.


Step 4: Run the Playbook

Execute the playbook using Ansible’s command-line interface. You can specify your inventory inline for simplicity:

ansible-playbook docker-playbook.yml -i "host1,host2," -u root

Replace host1 and host2 with your actual target hostnames or IP addresses.

Note:

  • The comma at the end of the inline inventory is required.
  • The option -u root sets the user Ansible uses to connect to the hosts; modify it based on your SSH setup.

Verifying Docker Installation

After running the playbook, you can verify Docker installation on each host by running:

ssh root@host1 docker --version
ssh root@host2 docker --version

You should see output similar to:

Docker version 26.1.3, build XXXXXXX

Conclusion

By following this structured method, you efficiently leverage Ansible to consistently and reliably install Docker across multiple servers, simplifying your infrastructure management.