Integration of Ansible with Docker

Rohit Raut
3 min readAug 19, 2020

--

Ansible

Ansible is the simplest way to automate apps and IT infrastructure. Application Deployment, Configuration Management, Continuous Delivery. Ansible is agentless, temporarily connecting remotely via SSH or Windows Remote Management (allowing remote PowerShell execution) to do its tasks.

TASK DESCRIPTION:

  • Configure the Yum for docker.
  • Starting and enabling of the docker services.
  • Pulling of the httpd server image from the Docker hub.
  • Running the httpd container image and exposing it to the public world.

prerequisite :

Installation of Ansible

pip3 install ansible

Create inventory

Ansible know about its target node from inventory file so we have to create inventory file and give inventory file path to ansible configuration file which we have to create in /etc/ansible folder with name ansible.conf.

In inventory file we have to give ip address,username and password of target nodes.

Create config file

here create a directory in /etc with name ansible, create file with name ansible.conf and give path of inventory to the configuration file.

we can verify ansible is configured on not using command

TO see all hosts run the following command.

Now andible is configured. so lets start to write a code in file having extension yml this file is called playebook.

Step 1: Configure YUM for docker

- name: "Docker setup,pull,and run the image"
hosts: all
tasks:
- name: "docker yum repository"
yum_repository:
name: "docker"
description: "docker rpm"
file: "docker"
baseurl: https://download.docker.com/linux/centos/7/x86_64/stable/
gpgcheck: no

Step 2: Installing docker

- name: "Docker Installation"
package:
name: "docker-ce-18.09.1-3.el7.x86_64"
state: present

Step 3: Starting Docker service

- name: "Starting Docker service"
service:
name: "docker"
state: started
enabled: yes

Step 4: Installing docker-py

Q] How ansible communicate with docker?

Ansible communicate with docker using python. so ansible need python docker SDK to communicate with docker that is why we need to install docker-py. To install docker-py.

- name: "Installing docker-py"
command: "pip3 install docker"

Step 5: Create directory and copy webpages in it

- name: "creating directory in managed Node"
file:
path: /root/webpages
state: directory
- name: "Copy to directory"
copy:
src: /root/playbooks/webpages/index.html
dest: /root/webpages

Step 6: Pull Httpd image

- name: "Pulling docker image"
docker_image:
name: "httpd"
source: pull

Step 7 : Launching docker image, exposing port 8080

- name: "run docker container"
docker_container:
name: "Container1"
image: httpd
exposed_ports:
- "80"
ports:
- "8080:80"
volumes:
- /root/webpages:/usr/local/apache2/htdocs

GitHub link : https://github.com/rohitraut3366/Ansible-Docker-integration.git

Thank You Mr. Vimal Daga Sir for giving such a task.

--

--

No responses yet