Git clone private projects using ssh

I am new to Docker and I have been trying to clone a private project using ssh without success. Here is my Dockerfile,

FROM continuumio/anaconda3
RUN apt-get update && apt-get install -y wget git openssh-client

ARG SSH_PRIVATE_KEY
RUN mkdir /root/.ssh && chmod -R 700 /root/.ssh
RUN /bin/bash -c cat "${SSH_PRIVATE_KEY}" >> /root/.ssh/id_rsa 
RUN chmod 600 /root/.ssh/id_rsa && echo "StrictHostKeyChecking no" > /root/.ssh/config
RUN ssh-keyscan github.com >> /root/.ssh/known_hosts
# RUN eval "$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa

WORKDIR /workdir
RUN git clone git@github.com:USERNAME/REPO_NAME.git

To build, I use the command docker build -t app --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_rsa)" .However, it always return Load key "/root/.ssh/id_rsa": invalid format. To check if it is related github, I add the commented line RUN eval "$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa but it also return the same error.

I appreciate for your help.

Hello @tck199732 ,

please note cat may not be applicable to a variable.

please find updated docker file below.

FROM continuumio/anaconda3
ARG SSH_PRIVATE_KEY=""
RUN apt-get update && apt-get install -y wget git openssh-client
# ARG SSH_PRIVATE_KEY
RUN mkdir /root/.ssh && chmod -R 700 /root/.ssh
RUN echo "${SSH_PRIVATE_KEY}" >> /root/.ssh/id_rsa
RUN echo ${SSH_PRIVATE_KEY}
RUN chmod 0400 /root/.ssh/id_rsa && echo "StrictHostKeyChecking no" > /root/.ssh/config
RUN cat /root/.ssh/id_rsa
RUN ssh-keyscan github.com >> /root/.ssh/known_hosts
# RUN eval "$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa

WORKDIR /workdir
RUN git clone git@github.com:USERNAME/REPO_NAME.git

RUN ls -l

I hope this helps.

thanks

Do you really want your key to be persisted in the final image? Or is it supposed to be a multi-stage build, where the cloning and building takes place in a stage and the final result is copied into the final stage?

There is actually a build in way to mount ssh private keys as secrets into the build containers: https://docs.docker.com/engine/reference/builder/#run---mounttypessh

Note: # syntax=docker/dockerfile:1 in the first line is important, it needs to be present in the Dockerfile to make this special mounts work!

Hi everyone,

@alishah730 I realized I made a mistake when writing ssh key into the target file.

# prints empty line to the file
RUN  /bin/bash -c echo "${SSH_PRIVATE_KEY}" >> /root/.ssh/id_rsa
# works
RUN /bin/bash -c "echo '${SSH_PRIVATE_KEY}' >> /root/.ssh/id_rsa"

@meyay Thanks. I understand private key should not be exposed and this script is just a test. I was planning for a multi-stage build but it seems your suggestion is cleaner.

Sorry for making the stupid mistake. Thanks.