How to Seamlessly Automate Docker using Ansible.

Ansible:-

Docker:-

Lets perform a task of how to use docker with the ansible playbook, in this playbook we have to configure the docker on the target node and also launch a docker container having httpd image on the same target node using the playbook. Lets first see the task:-

Task:-

🔰Write an Ansible PlayBook that does the following operations in the managed nodes:
🔹 Configure Docker
🔹 Start and enable Docker services
🔹 Pull the httpd server image from the Docker Hub
🔹 Run the docker container and expose it to the public
🔹 Copy the html code in /var/www/html directory
and start the web server

Solution:-

Prequisites for the following task:-

  • You must have the ansible configured in the base os.
  • Also in the inventory file of the ansible must have configured the target node.

Follow the bellow mentioned steps to solve the above task,

Step 1:Create a playbook using the following cmd:-

vim dock_ans.yml

The playbook must have the “.yml” extenstion.

Step 2:Configurethe Docker repository:-

In this step we have to configure the docker repository, for this use the “yum_repository” module of the ansible.

Code:-

Output:-

Step 3:Install the Docker:-

For this we have to use the “command” module instead of the “package” module because in the package module we cannot pass the option while installing the software.

Code:-

Output:-

Step 4:Start the Docker service:-

For starting the service use the “service” module of the ansible.

Code:-

Output:-

Step 5:Copy the data(html page code) to the target node:-

For copying the data we can use the “copy” module of the ansible.

Code:-

Output:-

Step 6:Launch a docker container:-

For launching the docker container we can use the “docker_container” module of the ansible. While launching the container we have to attach the volume containing the webpage to the volume of the container that can be access by the outside world , also have to enable the pnatting service for that container.

Code:-

The above code will automatically will download the httpd image from the docker hub.

Output:-

Full Code:-

To run the Code use the following command:-

ansible-playbook dock_ans.yml

Output:-

The web Page that is present on the docker container will be like:-

Conclusion:-

Ansible is the easiest way to automate Docker in your development environment. Ansible allows you to automate your Docker container build and deployment method in means that you’re likely doing manually. Ansible seamlessly automates Docker and operationalizes the process of building and deploying containers.

Thanks For Reading…….