Configuring Webserver Inside Docker Container By Auto-Updating Ansible Inventory File
Task - Create An Ansible Playbook that will Retrieve New Container IP and Update the Inventory. So further Configuration of Web server could be done inside that Container.
To accomplish this task we have to:
First, launching a Docker container.
Then we have to retrieve container IP and save it to the inventory.
And then using Ansible we have to configure the Docker container.
Now if we want to configure docker containe,r Ansible uses ssh and ssh is by default not enabled in the container. so we can use a non-official image where the ssh is already enabled or create our own with ssh enabled.
Now here we have our playbook dockerIP.yml:
docker.yml:
- hosts: localhost
tasks:
- name: Stopping SElinux Services
selinux:
policy: targeted
state: permissive
- name: Starting Docker Services
service:
name: docker
state: started
enabled: yes
- name: Starting Docker Container
docker_container:
name: sshos
image: myos/ssh
state: started
interactive: yes
command: /usr/sbin/sshd -D
- name: Retrieving Docker IP
docker_container_info:
name: sshos
register: result
- debug:
var: result.container.NetworkSettings.IPAddress
- name: Updating Inventory File By Docker Container IP
blockinfile:
dest: "/root/Extra/ip.txt"
block: |
[docker]
{{ result['container']['NetworkSettings']['IPAddress'] }} ansible_user=root ansible_password=docker123 ansible_connection=ssh
- name: Refreshing Inventory
meta: refresh_inventory
- hosts: docker
tasks:
- name: Installing Packages
package:
name: httpd
state: present
- name: Starting webserver
command: /usr/sbin/httpd
- name: Copying
copy:
src: 'home.html'
dest: '/var/www/html/index.html'
In this playbook:
Ansible will launch the container from the ssh enabled custom docker image while also start docker services. Even with the ssh configured in the image when we launch a new container from the image at that time the ssh service is stopped so before configuring anything in the docker we have to start ssh service to do that the command used is: /usr/sbin/sshd -D in the code -D will run this service alongside the bash.
And in the end the code will retrieve the Docker IP and add it to the Inventory with the group name Docker and ansible will refresh the Inventory.
Then, it will install httpd package and start its services and then copy html files from our computer to the container.
When we run the playbook:
Here is docker container IP which is retrived:
Now we check by searching the Docker IP in Browser:
Now the task is successful, I would like to thanks Mr Vimal Daga sir for providing such information.