Update Ansible inventory with new container IP of Docker
In this article, we’ll see how to fetch the docker container IP after provisioning and how to update it in the inventory of Ansible, and also configure the apache web server on the docker container with Ansible playbook.
In this example, I am going to use a centos image with SSH enabled because Ansible connects with Linux OS with SSH protocol but the centos image has no SSH available by default. first, we will create our own Dockerfile with SSH enabled.
Dockerfile
Here is a code for Dockerfile. Copy this code and save it as Dockerfile. Then run docker build . -t <image-name>:<tag> command, it will build the image with SSH enable. In my case, I have given ssh-centos:v1 name.
FROM centos:latestRUN yum install net-tools -yRUN yum install openssh-server -yRUN ssh-keygen -ARUN yum install passwd -yRUN echo root | passwd root --stdinCMD ["/usr/sbin/sshd", "-D"]
ansible.cfg
Create ansible.cfg in your workspace, so that ansible will take all the configuration from this file.
[defaults]
inventory=inventory
host_key_checking=false
remote_user=root
ask_pass=true
Inventory
Just write group name and save it as inventory without any extension.
[container]
docker-container.yml
This YAML file will launch the docker container for us but the host OS must have python3 and docker sdk installed, if you don't have than install python3 and then install docker with pip3 install docker.
---
- hosts: localhost
vars:
- container_name: "firstContainer"
- image_name: "ssh-centos:v1"
tasks:
- docker_container:
name: "{{ container_name }}"
image: "{{ image_name }}"
state: started
register: container_info
- lineinfile:
path: inventory
insertafter: '^\[container]'
firstmatch: yes
line: "{{ container_info.ansible_facts.docker_container.NetworkSettings.IPAddress }}"
state: present
docker_container module will launch a container on the localhost and register keyword stores all the information about container. For now, we only needs the IP of the container. lineinfile module will takes the IP from the container_info variable and write the IP into the inventory file.
docker-web-server.yml
---
- hosts: container
vars:
- document_root: "/var/www/html"
tasks:
- name: Installing the httpd
package:
name: httpd
state: present
- name: Content for web
copy:
dest: "{{ document_root }}/index.html"
content: "Automation with ansible!!!"
register: result
- name: Starting httpd service
command: "/usr/sbin/httpd"
when: result.changed == "true"
This YAML file will configure the apache web server on the launched container.
Final Output
That’s it guys. I have mentioned github repo link for download the codes
Thanks for the reading…