0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VSCodeでSSH先のDockerコンテナの指定ディレクトリを一瞬で開きたい【2023年度版】

Last updated at Posted at 2023-11-09

TL;DR

ターミナルから

$ code --folder-uri vscode-remote://someurl/path/to/directory

これはなに

VSCodeでローカルのファイルを見る時には

$ code path/to/directory

と一瞬で開ける

それに比べてSSH先のファイルを見るとなると左下の緑の><を押して、ホストに接続して、コンテナを開いて、とボタンをポチポチしないと......とぼやいていたのですが、全然そんなことなかったので備忘録

やり方

  1. JSONを見つける
    VSCodeは過去に開いたworkspaceをJSONで記憶しています
    Macなら~/Library/Application\ Support/Code/User/globalStorage/storage.jsonにあります
  2. URIを探す
    JSON内にて、
    最後に開いたウィンドウ "lastActiveWindow" とか
    過去に開いたことのある一覧 "profileAssociations" とかを見つけてください。
    おそらく他の場所にもありますが、とにかく以下のような文字列を探します

最近Remote-SSHを使用してSSH接続をしてなんらかのフォルダを開いたのであれば
vscode-remote://ssh-remote%2B{.ssh/configに設定したHost名}/path/to/directory

Dev Containersを使用してDockerコンテナを開いたのであれば
vscode-remote://dev-container%2{エンコードされた文字列}/path/to/directory

vscode-remote://attached-container%2B{エンコードされた文字列}@ssh-remote%2B{.ssh/configに設定したHost名}/path/to/directory

の場合もあるっぽい

ちなみに、16進数にエンコードされた部分の文字列をデコードして復元すると

{"hostPath":"docker-compose.yamlを置いていたディレクトリへの絶対パス","localDocker":false,"configFile":{"$mid":1,"path":".devcontainer.jsonへの絶対パス","scheme":"vscode-fileHost"}}

3.ターミナルでcode --folder-uri + URIを打つと完成

# 例
$ code --folder-uri vscode-remote://dev-container%2{エンコードされた文字列}/path/to/directory

注意点として、コンテナが起動していない場合はVSCodeが立ち上がったのちDev Containersがエラーを吐きます。再度コンテナを起動させてからやり直すと解消します

その他

勘の良い方はお気付きでしょうが、/path/to/directoryで指定するディレクトリを変えると、開くディレクトリを変えることができます

.zshrcの例(alias名や関数名は適宜変えてください)

# 毎回同じディレクトリで足りるやつ
alias remote_host_dir='code --folder-uri vscode-remote://ssh-remote%2B{.ssh/configに設定したHost名}/path/to/directory'

# たまにディレクトリを可変にしたいやつ
open-remote-container() {
    if [ "$1" = "--folder" ] && [ -n "$2" ]; then
        code --folder-uri vscode-remote://ssh-remote%2B{.ssh/configに設定したHost名}/home$2
    else
        code --folder-uri vscode-remote://ssh-remote%2B{.ssh/configに設定したHost名}/home
    fi
}

# 使用例
#   /homeが開く
#   $ open-remote-container
#   /root/some_dirが開く
#   $ open-remote-container --folder /root/some_dir

良いVSCode生活を!

Reference

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?