How to Use Ansible to Install and Set Up Docker on Ubuntu 18.04

Introduction

Due to the fact that modern application environments have disposable nature, server automation plays an essential role in systems administration. CM tools like Ansible are instrumental in reducing human error associated with manual setups by setting standard procedures for new servers. 

The Ansible offers architecture, which does not require the installation of special software on nodes. Moreover, it provides a robust set of built-in modules and features that facilitate automation scripts writing.

The actual tutorial will guide you upon the use of Ansible to automate the process described in our other tutorial How To Install and Use Docker on Ubuntu 18.04. The primary mission of Docker as an application is to simplify managing application processes in containers, which help running your applications in resource-isolated processes. Containers can be compared to virtual machines; however, they are more resource-friendly, more portable, and more dependent on the host operating system.

Before you proceed, check if your Ansible control node connects to our Ansible host(s) and execute commands there. See Step Three of our How to Install and Configure Ansible on Ubuntu 18.04 to make the test.

What Does this Playbook Do?


With this Ansible playbook you will not have to run through the procedure of manual Docker Installation described in How To Install and Use Docker on Ubuntu 18.04.

The below actions will be performed on your Ansible hosts when running this playbook:

  • aptitude installation. This alternative manager is preferred by Ansible instead of the apt package manager.
  •  System packages installation.
  • Docker GPG APT key installation .
  • Adding the official Docker repository to the apt sources.
  • Docker installation .
  • Using pip to install the Python Docker module.
  • Pulling the default image defined by default_container_image from Docker Hub.
  • Creating various containers specified by the variable create_containers, using the image specified by default_container_image by each of them, and executing the command specified in default_container_command in every new container.
  • As a result, a number of containers will be created.These containers will be based on the options defined within your configuration variables.

Instructions to Playbook


First of all, go to the do-community/ansible-playbooks repository to get the Docker playbook and its dependencies. After that, clone this repository inside the Ansible Control Node, to a local folder.

If this repository has been already cloned before according to a different guide, access your ansible-playbooks copy that already exists and type a git pull command to ensure that its contents are updated:

$ cd ~/ansible-playbooks
$ git pull

If you are using the do-community/ansible-playbooks repository for the first time, clone the repository to your home folder:

$ cd ~
$ git clone https://github.com/do-community/ansible-playbooks.git
$ cd ansible-playbooks

The files we need in are kept the folder docker_ubuntu1804  that looks like shown below:

docker_ubuntu1804
├── vars
│   └── default.yml
├── playbook.yml
└── readme.md

Each of these files has its function:

  • vars/default.yml: it is a variable file that serves to customize the settings of the playbook.
  • playbook.yml: it is the file of the playbook. It contains the tasks that the remote server(s) will execute.
  • readme.md: it is text file with the information about this playbook.

In order to customize our Docker setup, you need to edit the variable file of the playbook. Access the directory docker_ubuntu1804 and use your favourite command line editor to open the vars/default.yml:

$ cd docker_ubuntu1804
$ nano vars/default.yml

Some  variables might need to be changed:

vars/default.yml
---
create_containers: 4
default_container_name: docker
default_container_image: ubuntu
default_container_command: sleep 1d

Here is a short explanation of these variables and how they can be altered:

- create_containers: means the number of containers you want to create.
- default_container_name: container name set by default.
- default_container_image: default Docker image you want to use to create the containers.
- default_container_command: default command that will be used to run on new containers.

When finished configuring the variables of the vars/default.yml file, save and close it. If nano was used, press CTRL + X, then Y, and then ENTER.

Now, this playbook can be run on one or more servers. By default, the majority of playbooks are set to be executed on every server in your inventory. Thus, the -l flag can be used to ensure that only a single server, or a subset of servers, will be affected by the playbook. In addition, by using the -u flag, you can specify which user on the remote server is used to execute the commands of the playbook on the remote hosts.

In case you want to execute the playbook only on server1, connecting as sammy, type the command below:

$ ansible-playbook playbook.yml -l server1 -u sammy

You should see the output alike:

Output
...
TASK [Add Docker GPG apt Key] ********************************************************************************************************************
changed: [server1]

TASK [Add Docker Repository] *********************************************************************************************************************
changed: [server1]

TASK [Update apt and install docker-ce] **********************************************************************************************************
changed: [server1]

TASK [Install Docker Module for Python] **********************************************************************************************************
changed: [server1]

TASK [Pull default Docker image] *****************************************************************************************************************
changed: [server1]

TASK [Create default containers] *****************************************************************************************************************
changed: [server1] => (item=1)
changed: [server1] => (item=2)
changed: [server1] => (item=3)
changed: [server1] => (item=4)

PLAY RECAP ***************************************************************************************************************************************
server1                  : ok=9    changed=8    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

As soon as the playbook stops running, use SSH to log in to the server that is provisioned by Ansible. Then check whether the containers were created by runnig docker ps -a:

$ sudo docker ps -a

The following output should appear:

Output
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
a3fe9bfb89cf        ubuntu              "sleep 1d"          5 minutes ago       Created                                 docker4
8799c16cde1e        ubuntu              "sleep 1d"          5 minutes ago       Created                                 docker3
ad0c2123b183        ubuntu              "sleep 1d"          5 minutes ago       Created                                 docker2
b9350916ffd8        ubuntu              "sleep 1d"          5 minutes ago       Created                                 docker1

This output means the playbook was fully executed on this server and informs about the succssfull creation of all the containers defined in the playbook.

The Contents of the Playbook


Docker server setup is featured in this tutorial in the folder docker_ubuntu1804 inside the repository DigitalOcean Community Playbooks. Click the Raw button in the top of each script to download or copy the script contents directly.

Also, for your convenience, we have included the associated files of the playbook and its full contents.

vars/default.yml


The variable file default.yml contains values that will be used during Docker setup on your server.

vars/default.yml
---
create_containers: 4
default_container_name: docker
default_container_image: ubuntu
default_container_command: sleep 1d

playbook.yml


All tasks from this setup are specified in defined.playbook.yml file. It begins with the definition of the group of servers (all) that this setup targets. Further, become: true is used to specify that, by default, tasks must be executed with privileges (sudo). Lastly, configuration options are loaded using the vars/default.yml variable file.

playbook.yml
---
- hosts: all
  become: true
  vars_files:
    - vars/default.yml

  tasks:
    - name: Install aptitude using apt
      apt: name=aptitude state=latest update_cache=yes force_apt_get=yes

    - name: Install required system packages
      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 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 bionic stable
        state: present

    - name: Update apt and install docker-ce
      apt: update_cache=yes name=docker-ce state=latest

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

    - name: Pull default Docker image
      docker_image:
        name: "{{ default_container_image }}"
        source: pull

    # Creates the number of containers defined by the variable create_containers, using values from vars file
    - name: Create default containers
      docker_container:
        name: "{{ default_container_name }}{{ item }}"
        image: "{{ default_container_image }}"
        command: "{{ default_container_command }}"
        state: present
      with_sequence: count={{ create_containers }}

This playbook can be modified according to your individual needs in your workflow. For instance, to push images to Docker Hub, you can use the module docker_image or the module docker_container to set up container networks.

  • DOCKER, CONFIGURATION MANAGEMENT, ANSIBLE, UBUNTU 18.04
  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 18.04

Introduction ‘LAMP” is a stack of open-source software. Typically, it is installed together in...

How To Install Linux, Nginx, MySQL, PHP (LEMP stack) on Ubuntu 18.04

Introduction LEMP is a pack of software. It is generally used to serve dynamic web applications...

How To Install Nginx on CentOS 7

What is Nginx Nginx is server software that is characterized by high performance, flexibility,...

How To Install Node.js on Debian 10

Introduction Node.js a Javascript platform that allows easy creation of networked applications...

How To Install Node.js on Ubuntu 18.04

Introduction Node.js is a JavaScript platform that is used to allow users to build network...