Ansible playbook that will update the Container IP (dynamically inventory) and Configure Webserver inside the Container
2 min readAug 27, 2022
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.
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.