DEV Community

Alex Antsiferov
Alex Antsiferov

Posted on • Edited on

VS Code devcontainer with an external terminal: SSH agent howto

I'm not a huge fan of VS Code's internal terminal.

I keep bumping into its various bugs, like disappearing characters, cmd-V pasting into the wrong window, or the terminal getting closed when switching branches (with scm.workingSets feature enabled).
And really, I find the terminal an unnecessary bloat for a code editor.

That said, we do use VS Code and devcontainers at work.
I won't get into the advantages and disadvantages, let's say it's a given.

In order to use an external terminal with a devcontainer we need something like this, works just fine:

CONTAINER_ID=$(docker ps --format "table {{.ID}}\t{{.Names}}" | grep "my-container-name" | awk '{print $1}')

docker exec -ti -w /workspaces/my-project "$CONTAINER_ID" /bin/zsh
Enter fullscreen mode Exit fullscreen mode

But there's one thing I couldn't get to work in an external terminal -- the SSH agent. Not being able to git pull is annoying!

VS Code mounts the host SSH agent's socket to the container. It also sets SSH_AUTH_SOCK var, but only for the internal terminal:

vscode ➜ /workspaces/my-project (main) $ echo $SSH_AUTH_SOCK
/tmp/vscode-ssh-auth-e85d0936-746e-465d-8382-cbf0bb69b476.sock
Enter fullscreen mode Exit fullscreen mode

So here's the workaround: we find it in /tmp and set SSH_AUTH_SOCK in our docker exec command:

CONTAINER_ID=$(docker ps --format "table {{.ID}}\t{{.Names}}" | grep "my-container-name" | awk '{print $1}')

docker exec -ti \
  -w /workspaces/my-project \
  "$CONTAINER_ID" \
  sh -lc '
    for sock in /tmp/vscode-ssh-auth-*.sock; do
      [ -S "$sock" ] || continue
      SSH_AUTH_SOCK="$sock" ssh-add -l >/dev/null 2>&1 && {
        export SSH_AUTH_SOCK="$sock"
        echo "Using SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
        break
      }
    done

    if [ -z "$SSH_AUTH_SOCK" ]; then
      echo "No working VS Code SSH agent socket found"
    fi

    exec /bin/zsh
  '
Enter fullscreen mode Exit fullscreen mode

A bit hacky, but it does the job! Enjoy working from your favorite terminal!

Top comments (1)

Collapse
 
wetterkrank profile image
Alex Antsiferov

Aha, turns out, VS Code leaves old sockets in /tmp, so we can't take the first match, have to find an active symlink or test all sockets with ssh-add -l to find the working one.
The snippet is updated.