'docker build --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_rsa)" returning empty

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



Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shammir
Solution 2 ignacio