DEV Community

Alex Antsiferov
Alex Antsiferov

Posted 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 '
    SOCK=$(ls /tmp/vscode-ssh-auth-*.sock 2>/dev/null | head -n1)
    if [ -n "$SOCK" ]; then
      export SSH_AUTH_SOCK="$SOCK"
      echo "Using SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
    else
      echo "No VS Code SSH socket found"
    fi
    exec /bin/zsh
  '
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)