How to setup Ansible Dynamic Inventory for Docker using Ansible Plugin?

To provision a container using Docker, we mostly go with manual way using Docker CLI or used Dockerfile to built own pre-configured Docker Image to launch container.

In this article, we are going to learn how to configure server inside docker container using Ansible. Ansible is a radically simple IT automation engine that automates cloud provisioning, configuration management, application deployment, intra-service orchestration, and many other IT needs.

Task:

Setup Ansible Dynamic Inventory Plugin for Docker.

Prerequisites:

  • Assuming that Ansible is already running properly.
  • Docker Engine is installed and running in Host VM.

Steps:

1. Install Docker SDK for Python:

The SDK needs to be installed on the machines where the modules and plugins are executed, and for the Python version(s) with which the modules and plugins are executed.

You can install the Docker SDK for Python 3.6 or later as follows:

$ pip3.8 install docker

2. Install Required Ansible-collection in your host to use Inventory plugin:

community.docker.docker_containers: Ansible Dynamic Inventory Plugin for Docker Container

To install it use:

$ ansible-galaxy collection install community.docker

3. Setup Ansible Config file:

In /etc/ansible, create config file for Ansible named ansible.cfg:

$ cat /etc/ansible/ansible.cfg
===============================================
[defaults]inventory = /etc/ansible/hosts
roles_path = /etc/ansible/roles
host_key_checking = False

4. Setup Inventory Plugin for Docker:

Now, first create one directory named hosts in /etc/ansible. Inside this directory, create a YAML configuration file that ends with docker.[yml|yaml].

$ cat /etc/ansible/hosts/main_docker.ymlplugin: community.docker.docker_containers
docker_host: unix://var/run/docker.sock

By default, it uses Docker-API to connect to container. To check more about it, click here

5. Test the setup that it worked or not:

For testing, I’m launched one container using Docker CLI first…

$ docker run -dit --name test centos:latest

Now run command to check container using Ansible Plugin:

$ ansible-inventory --graph

Now you simply run your playbook in docker container using test as host.✌

To know more about the launch and configure docker container using Ansible, please check below article…

Please do Clap if you enjoyed the article…

Feel free to connect on linkedin…😊

Having any issues related to article, please DM me…

Tech Enthusiasts, Passion to learn and share