SSH agent forward into docker container on macOS

Preface

I am used to git ssh remote URL, in case of public and private repositories either from GitHub or gitlab (those projects are either contributed or authored by me). Beside in my current company (Zitelab ApS), we have our gitlab enterprise edition server which is hosted into our own cloud and most of the repositories are internally accessible by our team exclusively. The main reason for using ssh remote URL is to avoid entering username and password at each time of push, pull (required over https remote URL)

Why SSH agent for docker container

For me as a new macOS user, for the first time, I faced problem while trying to clone some of the repositories from the inside docker container. My idea was to copy my local ssh key pair into container´s .ssh directory (not secure huh!) and help from the great teacher Google found many solutions for me like Pass local machine’s SSH key to docker container, Using SSH keys inside docker container and so on, however honestly speaking I was not able to implement the ssh key pair copying idea (may not be tried so hard, because I found a better and safe idea later?)

Finally took the idea of ssh agent forwarding (which method I used already in the vagrant based machine). In my opinion, this approach is the best fit for fulfilling my purpose at least.

Configure SSH agent forward in Mac Machine

I refer ´host´ as my development machine it-self and ´guest´ is referred to the docker container. Ignore this the step if you have already.

Setup Host Machine´s ssh config (~/.ssh/config) (Optional)

Example wildcard(*) applicable for all host
Host *
     ForwardAgent yes
     IdentityFile ~/.ssh/id_rsa
Example Certain Host
Host gitlab.com
     ForwardAgent yes
     IdentityFile ~/.ssh/id_rsa_gitlab
Example Certain IP ranges
Host 192.168.*
ForwardAgent yes
IdentityFile ~/.ssh/id_rsa_gitlab

Setup in Docker-compose file

docker-compose.yml

version: '3'
services:
  my_service_name:
    build: .
    environment:
      - SSH_AUTH_SOCK="${SSH_AUTH_SOCK}"
    volumes:
      - ${SSH_AUTH_SOCK}:${SSH_AUTH_SOCK}

Enable SSH Forwarding directly from docker command

docker run --rm -t -i  -v $SSH_AUTH_SOCK:${SSH_AUTH_SOCK} -e SSH_AUTH_SOCK=${SSH_AUTH_SOCK}  <your container tag>

Disclaimer

My machine is MacBook pro 15 2109 and with Mojave OS (at the time of writing), However, I saw on the internet some complaints about not working properly but in my case, it is working perfectly.

References

  1. Can we re-use the OSX ssh-agent socket in a container?