How to attach a remote container using vscode command line?

Viewed 1698

I want to use a command line tool to attach a remote container. I tried this command (see below), but it's of no use. Does anyone know the correct command?

code --folder-uri vscode-remote://dev-container+4aaf623ee98a52fa311226a2c619be19addfa221c090b9a3bc37e7cba03a7fce/easycv
3 Answers

That string of characters after dev-container+ is an ascii path to your dev container folder encoded in hexadecimal.

To open a folder in a container you can use the following style command:

code --folder-uri=vscode-remote://dev-container%2B{path-in-hex}/{path-inside-container}

For example to open the folder /workspaces/test in the development container located in /Users/jkells/projects/vscode-devcontainer I use the following CLI command.

code --folder-uri=vscode-remote://dev-container%2B2f55736572732f6a6b656c6c732f70726f6a656374732f7673636f64652d646576636f6e7461696e6572/workspaces/test

To convert the string /Users/jkells/projects/vscode-devcontainer into the hexadecimal 2f55736572732f6a6b656c6c732f70726f6a656374732f7673636f64652d646576636f6e7461696e6572 you can use the following command

printf /Users/jkells/projects/vscode-devcontainer | od -A n -t x1 | tr -d '[\n\t ]'

To automate this, I created this cross-plattform-ish solution:

https://github.com/geircode/vscode-attach-to-container-script

This solution creates the hex based on the name of the running container.

Windows CMD script:

docker run --rm geircode/string_to_hex bash string_to_hex.bash "<container_name>" > vscode_remote_hex.txt

set /p vscode_remote_hex=<vscode_remote_hex.txt

code --folder-uri=vscode-remote://attached-container+%vscode_remote_hex%/app

This shell script does the job:

#!/usr/bin/env bash

case $# in
1) ;;
*) echo "Usage: code-remote-container <directory>"; exit 1 ;;
esac

dir=`echo $(cd $1 && pwd)`
hex=`printf ${dir} | od -A n -t x1 | tr -d '[\n\t ]'`
base=`basename ${dir}`
code --folder-uri="vscode-remote://dev-container%2B${hex}/workspaces/${base}"

I have saved it under the name code-remote-container, which then e.g. can be used as:

code-remote-container .

which would open the current directory in the remote container.

Obviously this expects that the remote container has already been setup for vsc.

Related