5

I want to be able to read the contents of the file ~/.ssh/id_rsa and pass the same to my build stage of the image. When I use the command docker build --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_rsa)" and then I try to echo that inside the container during a build, I get empty.

RUN echo "$SSH_PRIVATE_KEY" > /priv_key \
    && cat /priv_key

the result is

Step 6/14 : RUN echo "$SSH_PRIVATE_KEY" > /priv_key     && cat /priv_key
 ---> Running in c8d6e3c88cd8

Removing intermediate container c8d6e3c88cd8

In the dockerfile I have ARG SSH_PRIVATE_KEY.

But when I use a dummy text like docker build --build-arg SSH_PRIVATE_KEY="dummy text" I can see it in the logs.

This causes my private key to be in invalid format since it is empty. RUN echo "${SSH_PRIVATE_KEY}" >> /root/.ssh/id_rsa

What am I doing wrong or what is it that am not doing? Thank you

Shammir
  • 927
  • 4
  • 17
  • 32
  • That's strange. The problem isn't with Docker since `dummy text` works. `"$(cat ~/.ssh/id_rsa)"` gets evaluated in the shell and gets passed to `docker build` just like `dummy text`. Does `echo "$(cat ~/.ssh/id_rsa)"` work? – h3yduck Dec 31 '19 at 08:08
  • It works on host - Mac OS. – Shammir Dec 31 '19 at 08:20
  • Does it work with other files/what it you use absolute path instead of `~`? – h3yduck Dec 31 '19 at 08:24
  • Very Strange. Even that is not working. – Shammir Dec 31 '19 at 08:35
  • I am on Mac OSX – Shammir Dec 31 '19 at 08:35
  • and what about `docker build --build-arg SSH_PRIVATE_KEY="$(echo something)"` / what shell do you use (`bash`, `zsh`, etc)? – h3yduck Dec 31 '19 at 08:57
  • 1
    This approach will compromise your ssh keys: anything you add to a Docker image can be trivially retrieved in plain text by anyone who has the image. Whatever your higher-level goal is, I would strongly suggest looking for a way to do it that does not require calling ssh from within the Dockerfile. – David Maze Dec 31 '19 at 09:06
  • Good point. What about attaching it as a volume when starting the container (if the key must be present in the docker container)? – h3yduck Dec 31 '19 at 09:12
  • I have use ONVAULT tool to handle the keys. Now it's working – Shammir Dec 31 '19 at 09:40
  • @DavidMaze its possible to use it and not expose private key with intermediate images, which are removed after final image is built. – Andrius Dec 14 '20 at 21:44

2 Answers2

3

I went ahead and used ONVAULT toool to handle the ssh keys. https://github.com/dockito/vault.

Also, I had misconfigured my .ssh/config file. The new file looks like this

Host *
  IgnoreUnknown AddKeysToAgent,UseKeychain
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_rsa 

I hope it helps someone in future.

Shammir
  • 927
  • 4
  • 17
  • 32
0

I could solve this by placing the ARG after defining the base image:

FROM ubuntu:18.04 as builder
ARG SSH_PRV_KEY

instead of

ARG SSH_PRV_KEY
FROM ubuntu:18.04 as builder
ignacio
  • 1,181
  • 2
  • 15
  • 28