Create an Ansible playbook that will retrieve container IP and update the inventory. So that further Configuration of the Webserver could be done inside that Container.

Ritesh Singh
3 min readDec 14, 2020

Prerequisite :

✅ Docker Installed.

Solution:

First, we need to make one playbook for updating inventory, for this, I have jinja 😅 in Playbook, After that use hosts name for configuring the web server in the docker container.

Step-1)Make one Docker image, add user, configure the password, and enable ssh

  • To make it simple I am using Dockerfile.
FROM ubuntu:latest
RUN apt update && apt install openssh-server sudo -y
RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1000 test
RUN echo "test:test"| chpasswd
RUN service ssh start
RUN echo "test ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
EXPOSE 22
CMD ["/usr/sbin/sshd","-D"]
  • Here I am using ubuntu:latest
  • For changing the pass of the user use chpasswd command.
  • After that also need to give power to this user, we need to add, USER_NAME ALL=(ALL) NOPASSWD:ALL in the /etc/sudoers.
  • Build the Dockerfile.
docker build -t NAME_OF_IMAGE .
  • After this launch one container 😉.
docker run -dit --name NAME_OF_CONTAINER -p 21:22 4444:80 NAME_OF_CONTAINER

Step-2)Retrieve the name and Ip of the container.


tasks:
- name: Retrive Name of Docker Container
shell: "docker ps --format '{% raw %}{{ .Names }}{% endraw %}'"
register: Name
- name: Retreive Ip of Docker Container
shell: "docker inspect --format '{%raw %}{{ .NetworkSettings.IPAddress }}{% endraw %}' $(docker ps --format '{% raw %}{{ .Names }}{% endraw %}')"
register: IP
  • Here I have used jinja because we need to retrieve the name and IP.
  • We need to register also because by using these vars we can update the inventory.

Step-3)Updating inventory

blockinfile:
path: /mydb/inventory.txt
block: |
{% raw %}[{% endraw %}{{ Name.stdout }}{%raw %}]{% endraw %}
{{ IP.stdout }} ansible_ssh_user=test ansible_ssh_pass=test
  • Here I have used the blackinfile module for configuring inventory.
  • I have also used jinja here because we need to write group name with [] brackets, for passing [] brackets as string in inventory, and {{ Name. stdout}}, {{ IP.stdout }} as variable 🤯.

Step-4)Configuring Webserver in the Docker container.

- hosts: NAME_OF_Container
become: yes
become_user: root
become_method: sudo
tasks:
- name: Installing webserver(apache2)
apt:
name: apache2
state: present
- name: Starting service
service:
name: apache2
state: started
  • I have used ubuntu:latest , so for ubuntu, I have installed apache2
  • Use privilege escalation for sudo.

Output 👊

  • Inventory updated
  • Use IP:4444(port)

Github Link

--

--