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
inventory = /myhosts/hosts.txt
host_key_checking = False
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,
- first using the yum_repository module of anisible we created a repo for installing docker-ce.
- name: Adding docker repository
description: repo for docker
2. then with yum module we are installing docker-ce, skipping the unsopported packages.
- name: Installing docker-ce
3. service module to start the docker services.
- name: Start docker service
4. package module to install python36 which will provide us pip3.
- name: Install python36 to provide pip3
5. Now using pip module to install the docker library of python.
- name: Install python docker library
6. We use docker_image module to pull httpd docker image.
- name: Pull httpd image
7. Using file module to create a directory at target node
- name: Create folder to copy code
8. copy module to copy some content in a file to the created directory in the previous task.
- name: Coping code
content: "<h1>Hello... This is new page</h1>"
9. firewalld module using which we are allowing a port 81 through the firewall
- name: Allow port through 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)
- name: Launching a new container
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),