Photo by Mohammad Rahmani / Unsplash

Installing Docker with Ansible on Ubuntu 20.04

Docker Aug 19, 2022

There is probably a blog post that should be made about Ansible that should come before this, but such is life! I got a question on YouTube on how to install Docker using Cloud-Init, which while a viable option, isn't my preferred method. I used to have a Cloud-Init config (the remnants of which I should remove from my Xen Orchestra panel...) but have since moved onto using Ansible.

My work flow for a new docker host is:

  • Create a new VM with my naming convention, something like maw-pnap-dev-docker01
  • Set choose my cloud-init template for user and networking to let me setup the VM with my SSH keys, the proper hostname, and the IP I want
  • SSH into my Ansible VM and edit my Ansible inventory file to add the new IP under my docker_standalone group which looks something like this...
[dkr_standalone]
10.10.0.15
10.10.0.16
10.10.0.17

[docker_hosts:children]
dkr_standalone
  • Run a git commit -a to upload it to Github which I use to version control my Ansible files, playbooks included
  • Then I run ansible-playbook playbooksinstall-docker.yaml which looks like...
---
- hosts: docker_hosts

  become: true
  tasks:
    - name: Install required system packages
      apt:
        pkg:
          - apt-transport-https
          - ca-certificates
          - curl
          - software-properties-common
          - python3-pip
          - virtualenv
          - python3-setuptools
        state: latest
        update_cache: true

    - name: Add Docker GPG apt Key
      apt_key:
        url: https://download.docker.com/linux/ubuntu/gpg
        state: present

    - name: Add Docker Repository
      apt_repository:
        repo: deb https://download.docker.com/linux/ubuntu focal stable
        state: present

    - name: Update apt and install docker-ce and docker-compose
      apt:
        pkg:
          - docker-ce
          - docker-compose
        state: latest
        update_cache: true

    - name: Install Docker Module for Python
      pip:
        name: docker

This will use Ansible to install the prerequisite software, add Docker's GPG key, add Docker's repo, install docker-ce and docker-compose via apt, and then install the Docker module for Python.

Most of that is self-explanatory but the last part might raise some questions. The Docker module for Python allows Ansible to interact with Docker! Since Ansible runs on Python the module is required for the interface. But, with it installed you can create containers, networks, volumes, perform updates, and more using Ansible!

There are some excellent references out there like Jeff Gerrling and his YouTube playlist on Ansible which goes into great detail on the software.

Tags