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.
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?
@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.