Configure Web Server inside Docker Container through Ansible

We will see how to 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 to the document root and start the web server.

So first, and obviously, ansible should be installed in the system (which is our contoller node), here I am using RedHat8 VM.

We should have a configuration file for ansible (/etc/ansible/ansible.cfg), where we have given the path of our inventory file (which contains information of our managed/target nodes). We added ‘host_key_checking = False’ so that when first time ansible connects to target it directly accept the connection without checking any key

An inventory can look like this, here I added one target node

Now lets see the tasks in the playbook that will do the complete setup,

  1. first using the yum_repository module of anisible we created a repo for installing docker-ce.

2. then with yum module we are installing docker-ce, skipping the unsopported packages.

3. service module to start the docker services.

4. package module to install python36 which will provide us pip3.

5. Now using pip module to install the docker library of python.

6. We use docker_image module to pull httpd docker image.

7. Using file module to create a directory at target node

8. copy module to copy some content in a file to the created directory in the previous task.

9. firewalld module using which we are allowing a port 81 through the firewall

10. docker_container to launch a container in detached mode, linking the folder that we created (containing our code) to the document root of apache and exposing the port 80 (on which httpd server is running) so can access it ussing port number 81 in base system (that’s why we added port 81 in the firewall rule)

Here is the complete playbook,

Now, running the created playbook

As we can see it is perfectly working (using the ip of base OS (host)on which docker is installed and with port number 81),

Thank you 😀 !

Tech and Programming, MLOps, DevOps Assembly Lines, Hybrid Multi Cloud, Flutter and Ansible Automation