Ansible playbook that will retrieve new Container IP and dynamically update the inventory and Configure Webserver inside the Container

Gursimar Singh
3 min readMar 27, 2021

--

Task Description:

14.2 Further in ARTH — Task 10 have to create an Ansible playbook that will retrieve new Container IP and update the inventory. So that further Configuration of Webserver could be done inside that Container.

Task 10: Configure Web Server in Docker and start services using Ansible Playbook | by Gursimar Singh | Medium

Let’s jump into the task

Initially the inventory file is empty

$ vim /etc/ansible/ansible.cfg

Ansible Playbook for container setup and auto updating of the inventory file:

$ vim play.yml

The playbook:

- hosts: localhost
vars_prompt:
- name: container_name
prompt: "Docker Container Name:"
private: no
vars:
- image_name: centos:v1
tasks:
- name: Creating Repo for yum
yum_repository:
name: docker
file: docker
description: Docker Yum Repo
baseurl: https://download.docker.com/linux/centos/7/x86_64/stable/
gpgcheck: no
- name: Install Docker-CE
command: "yum install -y docker-ce --nobest"
- name: starting docker services
service:
name: "docker"
state: started
enabled: yes
- name: Installing Docker Library
command: "pip3 install docker-py"
- name: pull an image
docker_image:
name: "{{ image_name }}"
source: pull
- name: "Launching {{ container_name }} Container"
docker_container:
name: "{{ container_name }}"
image: "{{ image_name }}"
state: started
interactive: yes
detach: yes
tty: yes
- name: "Container Info"
docker_container_info:
name: "{{ container_name }}"
register: docker_info
- debug:
var: docker_info.container.NetworkSettings.IPAddress
- name: "Retriving IP dynamically and updating in the inventory"
template:
src: "ip.txt"
dest: "/root/dockerip.txt"

Ansible Playbook to configure web page into the container:

$ vim web.yml

The Playbook:

- hosts: docker
tasks:
- name: "Installing Httpd service"
package:
name: "httpd"
state: present
- name: "Creating html file"
copy:
content : "<b><center>Webserver successfully configured</center></b>"
dest: "/var/www/html/index.html"
- name: "Starting Httpd Service"
command: "/usr/sbin/httpd"

Lets Run the Playbooks:

First let’s setup the container and set up the inventory file’

$ ansible-playbook play.yml

Inventory file is dynamically updated:

Now, let’s setup the webserver

$ ansible-playbook web.yml
"<IP>/web.html"

We have successfully completed the task and we can verify it by opening the webpage.

Github URL: ARTH-Program/Task 14/14.2 at main · gursimarh/ARTH-Program (github.com)

--

--

Gursimar Singh
Gursimar Singh

Written by Gursimar Singh

Google Developers Educator | Speaker | Consultant | Author @ freeCodeCamp | DevOps | Cloud Computing | Data Science and more

No responses yet