Enabling SSH inside docker container and accessing it with Ansible

Tirth Patel
3 min readMar 6, 2021

--

Even this is a very rare use case where we need to configure the container using ansible. Enabling ssh inside the container is not a good practice, but in some cases, we might need to do this.

Problem Statement

  1. Install docker engine on host computer.
  2. Configure a container with ssh enabled.
  3. Update the inventory file with container IP dynamically.
  4. Deploy a simple webapp on container using Ansible Playbook.

This article covers step by step guide to achieve our use case.

Writing Ansible Playbook to install docker engine.

Code to install docker and start docker service

After running the playbook, docker will be installed and the docker engine will be started.

Creating a SSH enabled container

We need to write a Dockerfile to create ssh enabled container. Lets start by understanding how we can configure ssh manually. So, we need openssh-server software for ssh service. Use command yum install openssh-server -y to install. Now we need to have passwd software to configure password for the user. Use command yum install passwd -y to install passwd. Now, change password of root user using passwd root, but it is a interactive command. So, we can use non-interactive command to directly fetch input from user. Use command echo “password”| passwd root — stdin. And then we can start the service by /usr/sbin/sshd and to make it permanently enable write the command inside /etc/rc.d/rc.local.

But this is time consuming so we decide to write a Dockerfile.

Now, run command docker build -t tirth1272/sshcontainer . (tirth1272 is just a username for docker hub, you have to keep your username)

Then you can do docker push <imagename> eg: docker push tirth1272/sshcontainer:latest

Now, writing a playbook to configure container.

After running, this code the inventory ip.txt will be updated.

Now, lets try to install any package inside this container. To do this make another yaml file.

Run this playbook and we will be able to configure the container according to our needs.

Thanks for reading :)

--

--

No responses yet