One of the aim of moving project’s deployment to docker, is to be able to build a image on any system without any manual setup. This articles shows how you can clone your private git repos inside a docker image without the need of username and password using SSH keys.
Generating the SSH key pairs
First we would generate a SSH key pair, which will be used by the docker image
$ mkdir ~/keys
$ ssh-keygen -t rsa -b 4096 -C "xxxxxx@yyyyy.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/tarunlalwani/.ssh/id_rsa): /home/tarunlalwani/keys/id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/tarunlalwani/keys/id_rsa.
Your public key has been saved in /home/tarunlalwani/keys/id_rsa.pub.
Now we have a keys folder generated in our home directotry with id_rsa
and id_rsa.pub
files.
Adding the target host fingerprints to known hosts
For security reason, each host that we would connect to using ssh, need to have finger prints in known_hosts
file. When we connect to a server for the firts time, it asks us to save those finger print. To do that automatically we need to use the ssh-keyscan
command
$ ssh-keyscan github.com >> ~/keys/known_hosts
$ ssh-keyscan gitlab.mydomain.com >> ~/keys/known_hosts
Adding the SSH keys on your git server
Make sure you add the content of the id_rsa.pub
we generated earlier into the allowed SSH keys of your git server(github or gitlab or bitbucket) settings
Creating the Dockerfile
We will create a new docker-git
folder in the home directory
$ mkdir ~/docker-git
$ mv ~/keys/ ~/docker-git/
$ cd ~/docker-git
Now let’s create a new Dockerfile
inside the docker-git
folder
Dockerfile
FROM ubuntu:14.04
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get -y update && apt-get -y install --no-install-recommends git ssh
WORKDIR /root
RUN mkdir -p /root/.ssh
COPY keys .ssh
RUN git clone git@gitlab.mydomain.com:root/seleniumplus.git
RUN unset DEBIAN_FRONTEND
CMD ["/bin/bash"]
Now if build and run the docker build command
$ docker build -t gittest:latest .
The output would come something like below
....
Step 8 : CMD /bin/bash
---> 93a05264fbca
Successfully built 93a05264fbca
To test same we can run the image using the tag
$ docker run -it gittest:latest
root@bf7ebb0619c0:~# ls
seleniumplus
root@bf7ebb0619c0:~# cd seleniumplus/
root@bf7ebb0619c0:~/seleniumplus# ls
README __init__.py selenium_automation.py
root@bf7ebb0619c0:~/seleniumplus#