Share SSH keys with VS Code Devcontainer running with Docker's WSL2 backend

Viewed 1012

I'm reading these docs on sharing SSH keys with a dev container, but I can't get it to work.

My setup is as follows:

  • Windows 10 with Docker Desktop 4.2.0 using the WSL2 backend

  • A WSL2 distro running Ubuntu 20.04

  • In WSL2, I have ssh-agent running and aware of my key:

    λ ssh-add -l
    4096 SHA256:wDqVYQshQBCG/Sri/bsgjEaUFboQDUO/9FJqhFMncdk /home/taschan/.ssh/id_rsa (RSA)
    

The docs say

the extension will automatically forward your local SSH agent if one is running

But if I do ssh-add -l in the devcontainer, it responds with Could not open a connection to your authentication agent.; and of course starting one (with eval "$(ssh-agent -s)") only starts one that doesn't know of my private key.

What am I missing?

2 Answers

I also had quite a lot of trouble to get this to work. The following steps might help troubleshooting:

  1. Check that ssh-agent is running on your host and the key is added

    Run ssh-agent -l on Windows and expect to see the name of your key

  2. Check that VSCode forwards the socket

    Search ssh-agent in the startup log. I had the message

    ssh-agent: SSH_AUTH_SOCK in container (/tmp/vscode-ssh-auth-a56c4b60c939c778f2998dee2a6bbe12285db2ad.sock) forwarded to local host (\\.\pipe\openssh-ssh-agent).
    

So it seems that VSCode is directly forwarding the Windows SSH agent here (and not an SSH agent running in your WSL).

I had basically the same issue. Running Windows 11 with WSL2 and my VSCode Devcontainer wouldn't show any ssh keys (running ssh-add -l inside the container showed an empty list) despite having Git configured on my host machine with working ssh keys.

For me, there were 3 separate instances of ssh-agent on my machine:

  • WSL2
  • Git Bash
  • Windows host This is the one VSCode is forwarding to the devcontainer

My existing ssh keys were set up inside Git Bash (as per Github's instructions) so running ssh-add -l only ever showed my ssh keys from inside a Git Bash terminal, nowhere else.

However, as explained in the previous answer, digging through the Devcontainer startup logs shows that VSCode is forwarding only the host machine's ssh-agent, it doesn't look at the WSL2 or Git Bash ones.

Solution: I suggest following the below Microsoft docs page. You need to enable an "Optional Feature" in Windows, then run a few commands in PowerShell (as admin) to activate the ssh-agent service. With this set up, the ssh-agent/ssh-add commands will work from a regular CMD terminal too. You can use these with the usual keygen commands etc to generate and add new keys on the host (I just ssh-add'ed the same keys generated by Git Bash originally). The added keys should immediately be detected by ssh-add -l inside the container.

https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_keymanagement

Related