Launching docker container and updating their ip in inventory file with Ansible

Rutujakonde
2 min readJan 8, 2021

--

🎯task description :

Launched docker container with Ansible and created 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.

This is the main ansible program

- hosts: localhost
vars_prompt:
- name: cont_name
prompt: “enter container name”
private: no
tasks:- name: “Creating docker repository”
yum_repository:
name: Docker
description: Docker Repo
baseurl: https://download.docker.com/linux/centos/7/x86_64/stable
gpgcheck: no
- name: “Downloading docker package”
package:
name: “docker-ce-18.09.1–3.el7.x86_64”
state: present
- name: Starting the Docker services
service:
name: “docker”
state: started
- name: Installing python3
package:
name: “python3”
state: present
- name: Installing Docker SDK
command: pip3 install docker
- name: stopping selinux
selinux:
policy: targeted
state: permissive
- name: pulling docker image
docker_image:
name: “httpd”
source: pull
- name: Launching a container
docker_container:
name: “{{ cont_name }}”
image: “httpd”
interactive: no
detach: yes
tty: no
- name: “retrieving IP of {{ cont_name }} container”
docker_container_info:
name: “{{ cont_name }}”
register: dinfo
- debug:
var: dinfo.container.NetworkSettings.IPAddress
- name: updating inventory with docker container ip
template:
src: ip.txt
dest: /root/ip.txt

dinfo[‘container’][‘NetworkSetting’][‘IPAdress’] is the variable that contains the container IP

ip.txt is the ansible template file that will dynamically update inventory.

(ip.txt)
[docker]
{{ dinfo[‘container’][‘NetworkSettings’][‘IPAddress’] }} ansible_user=root ansible_ssh_pass=root ansible_connection=ssh

THANK YOU!!!

--

--

No responses yet