Configuring Docker Container by Ansible
In this article we will see how to enable ssh in the container so that we can configure the container by the help of ansible.
Pre-Requisite
- Docker
- Docker SDK
- Python3
Follow the belows steps to make a customized image
- Pull Centos image using command
$docker pull centos:latest
2. Launch a container using this image
$docker run -dit --name os1 centos:latest
3. Login to the container os1
$docker attach os1
4. Install sshd in this container
$yum install openssh-server -y
5. Install passwd command
$yum install passwd -y
5. Set the root passwd
$passwd root
6. Make ssh service enable permanent, add the path /usr/sbin/sshd to /root/.bashrc
7. Exit from the container and commit this image with a different name and tag
$docker commit os1 centos_ssh:v1
Lets create a ansible playbook which launch the container and add thier ip in the inventory for further configuration.
- name: start a docker container
docker_container:
name: “os1”
image: centos_ssh:v1
state: started
ports:
— “81:22”
— “8080:80”
interactive: yes
tty: yes
restart: yes
register: x
- debug:
msg: this is the IP of docker {{ x.ansible_facts.docker_container.NetworkSettings.IPAddress }}- blockinfile:
path: /etc/ansible/myhosts.txt
block: |
[docker]
{{ x.ansible_facts.docker_container.NetworkSettings.IPAddress }} ansible_ssh_user=root ansible_ssh_pass=redhat
Now a container has been lauched with port 22 and 80 exposed, Lets check does this container is able to do ssh or or not for this i’m creating a playbook which will install and enable httpd service in the contianer.
- hosts: docker #here docker contains the ip of contianer
tasks:
— name: install httpd
package:
name: httpd
state: present
— copy:
src: /root/index.html
dest: /var/www/html/index.html
— command: /usr/sbin/httpd #to start service
Playbook runs successfully, now we can use this inventory for further configuration.
If you have any suggestion and query commen below
Thanku You!!!!