5

So I want to include an rsa key in my image so I can clone a git repo into my image when its building. But I really don't want to have to keep this key in the docker build repo. Does anyone have a good recommendation on how to handle this? From the docker documentation and various other threads it seems that there is no way to COPY files from outside of the build context. Apart from the following solutions that I am not interested in using:

How to include files outside of Docker's build context?

Is there a better solution to this? Or am I going to have to either keep the key in the build repo or build from the location of the of the rsa key I want to use?

I guess a possible way to do it would be to gitignore the key from the build repo and just put it in whenever I clone it, and make a note of it in the readme so other developers know to do this too.

--- My Solution ---

I don't think there is a "correct" answer for this but here was the solution I went with.

I create a linux user (somewhere) and generate a key for it. Then create a user on gitlab with only repo cloning rights. I add the public key from the linux user to the gitlab user. Then for the build I create the .ssh folder and copy in the users private key with a config file. I just store that users key in the docker build repo.

build steps:

RUN mkdir ~/.ssh
RUN touch ~/.ssh/known_hosts
RUN ssh-keyscan -t rsa gitlab_host > ~/.ssh/known_hosts
COPY ./ssh/config /root/.ssh
COPY ./ssh/id_rsa_app /root/.ssh
RUN chmod 600 /root/.ssh/id_rsa_app

ssh config file:

Host gitlab-app
  HostName gitlab_host
  IdentityFile /root/.ssh/id_rsa_app
  IdentitiesOnly yes

Now the git clone works inside of the build.

ThriceGood
  • 1,633
  • 3
  • 25
  • 43

1 Answers1

5

What about using a build argument? Do something like this in your Dockerfile:

ARG rsakey
RUN test -n "${rsakey}" && { \
      mkdir -p -m 700 /root/.ssh; \
      echo "${rsakey}" > /root/.ssh/id_rsa; \
      chmod 600 /root/.ssh/id_rsa; \
    } || :

Then, when you build the image, use the --build-arg option:

docker build -t sshtest --build-arg rsakey="$(cat /path/to/id_rsa)" .

This will inject the key into the image at build time without requiring it to live in your build context.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • thanks, this would be a workable solution. but we decided on creating a linux user called 'app', created a key for it and then created an 'app' user on our gitlab with only rights to clone repos. We then just put this key in our docker repos with a config file. see above. – ThriceGood Sep 18 '17 at 09:16
  • It's not an ideal solution. The content of the key is appended to the command line executing `docker build`, which might end up in some logs at the end (it happened to us building the docker images with gradle) – Nicolas Barbé Jul 06 '18 at 07:53