

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# リモート IDE のセットアップ
<a name="remote-access-local-ide-setup"></a>

管理者が の手順を完了したら[リモートアクセスを使用してリモート IDE を SageMaker スペースに接続する](remote-access.md)、リモート IDE をリモート SageMaker スペースに接続できます。

**Topics**
+ [ローカル環境をセットアップする](#remote-access-local-ide-setup-local-environment)
+ [リモート IDE に接続する](#remote-access-local-ide-setup-local-vs-code)
+ [インターネットアクセスなしでサブネットを使用して VPC に接続する場合](remote-access-local-ide-setup-vpc-no-internet.md)
+ [Studio スペースをフィルタリングする](remote-access-local-ide-setup-filter.md)

## ローカル環境をセットアップする
<a name="remote-access-local-ide-setup-local-environment"></a>

ローカルマシンに任意のリモート IDE をインストールします。
+ [Visual Studio Code](https://code.visualstudio.com/)
+ [Kiro](https://kiro.dev/)
+ [カーソル](https://cursor.com/home)

バージョンの要件については、「」を参照してください[IDE バージョンの要件](remote-access.md#remote-access-ide-version-requirements)。

## リモート IDE に接続する
<a name="remote-access-local-ide-setup-local-vs-code"></a>

リモート IDE からリモート SageMaker スペースへの接続を確立するには、管理者が である必要があります[リモートアクセスを設定する](remote-access-remote-setup.md)。管理者は、ユーザーが接続を確立するための特定の方法を設定します。設定された方法を選択します。

**Topics**
+ [方法 1: Studio UI からのディープリンク](#remote-access-local-ide-setup-local-vs-code-method-1-deep-link-from-studio-ui)
+ [方法 2: リモート IDE の AWS ツールキット](#remote-access-local-ide-setup-local-vs-code-method-2-aws-toolkit-in-vs-code)
+ [方法 3: SSH CLI 経由でターミナルから接続する](#remote-access-local-ide-setup-local-vs-code-method-3-connect-from-the-terminal-via-ssh-cli)

### 方法 1: Studio UI からのディープリンク
<a name="remote-access-local-ide-setup-local-vs-code-method-1-deep-link-from-studio-ui"></a>

ディープリンクを使用して接続を確立するには、次の手順に従います。

1. [Amazon SageMaker Studio を起動](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-launch.html#studio-updated-launch-console)します。

1. Studio UI で、該当スペースに移動します。

1. 任意の IDE の Open **in VS Code**、**Open in Kiro**、または **Open in Cursor** ボタンを選択します。希望する IDE がローカルコンピュータに既にインストールされていることを確認します。

1. プロンプトが表示されたら、IDE を開くことを確認します。IDE が開き、確認のための別のポップアップが表示されます。完了すると、リモート接続が確立されます。

### 方法 2: リモート IDE の AWS ツールキット
<a name="remote-access-local-ide-setup-local-vs-code-method-2-aws-toolkit-in-vs-code"></a>

 AWS Toolkit for Visual Studio Codeを使用して接続を確立するには、次の手順に従います。このメソッドは、VS Code、Kiro、および Cursor で使用できます。

1. リモート IDE (VS Code、Kiro、またはカーソル) を開きます。

1.  AWS Toolkit 拡張機能を開きます。

1. [AWSに接続](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/connect.html)します。

1.  AWS Explorer で、**SageMaker AI **を展開し、**Studio** を展開します。

1. Studio スペースを探します。

1. スペースの横にある **[接続]** アイコンを選択して開始します。
**注記**  
Toolkit for Visual Studio のスペースを停止して再起動し、まだ接続されていない場合は、リモートアクセスを有効にします。
サポートされている[インスタンスサイズ](https://docs.aws.amazon.com/sagemaker/latest/dg/remote-access.html#remote-access-instance-requirements)がスペースで使用されていない場合は、インスタンスを変更するように求められます。

### 方法 3: SSH CLI 経由でターミナルから接続する
<a name="remote-access-local-ide-setup-local-vs-code-method-3-connect-from-the-terminal-via-ssh-cli"></a>

次のいずれかのプラットフォームオプションを選択して、SSH CLI を使用して接続を確立する手順を表示します。

**注記**  
以下の手順に従う前に、 の最新バージョン[ローカルマシンの前提条件](remote-access.md#remote-access-local-prerequisites)がインストールされていることを確認してください。
の場合は[Bring your own image (BYOI)](studio-updated-byoi.md)、先に進む[イメージの要件](remote-access.md#remote-access-image-requirements)前に、「」に記載されている必要な依存関係がインストールされていることを確認してください。

------
#### [ Linux/macOS ]

シェルスクリプトを作成します (例: `/home/user/sagemaker_connect.sh`)。

```
#!/bin/bash
# Disable the -x option if printing each command is not needed.
set -exuo pipefail

SPACE_ARN="$1"
AWS_PROFILE="${2:-}"

# Validate ARN and extract region
if [[ "$SPACE_ARN" =~ ^arn:aws[-a-z]*:sagemaker:([a-z0-9-]+):[0-9]{12}:space\/[^\/]+\/[^\/]+$ ]]; then
    AWS_REGION="${BASH_REMATCH[1]}"
else
    echo "Error: Invalid SageMaker Studio Space ARN format."
    exit 1
fi

# Optional profile flag
PROFILE_ARG=()
if [[ -n "$AWS_PROFILE" ]]; then
    PROFILE_ARG=(--profile "$AWS_PROFILE")
fi

# Start session
START_SESSION_JSON=$(aws sagemaker start-session \
    --resource-identifier "$SPACE_ARN" \
    --region "${AWS_REGION}" \
    "${PROFILE_ARG[@]}")

# Extract fields using grep and sed
SESSION_ID=$(echo "$START_SESSION_JSON" | grep -o '"SessionId": "[^"]*"' | sed 's/.*: "//;s/"$//')
STREAM_URL=$(echo "$START_SESSION_JSON" | grep -o '"StreamUrl": "[^"]*"' | sed 's/.*: "//;s/"$//')
TOKEN=$(echo "$START_SESSION_JSON" | grep -o '"TokenValue": "[^"]*"' | sed 's/.*: "//;s/"$//')

# Validate extracted values
if [[ -z "$SESSION_ID" || -z "$STREAM_URL" || -z "$TOKEN" ]]; then
    echo "Error: Failed to extract session information from sagemaker start session response."
    exit 1
fi

# Call session-manager-plugin
session-manager-plugin \
    "{\"streamUrl\":\"$STREAM_URL\",\"tokenValue\":\"$TOKEN\",\"sessionId\":\"$SESSION_ID\"}" \
    "$AWS_REGION" "StartSession"
```

1. このスクリプトを次のとおり実行可能にします。

   ```
   chmod +x /home/user/sagemaker_connect.sh
   ```

1. `$HOME/.ssh/config` を設定して、以下のエントリを追加します。

```
Host {{space-name}}
  HostName 'arn:{{PARTITION}}:sagemaker:{{us-east-1}}:{{111122223333}}:space/{{domain-id}}/{{space-name}}'
  ProxyCommand '/home/user/sagemaker_connect.sh' '%h'
  ForwardAgent yes
  AddKeysToAgent yes
  StrictHostKeyChecking accept-new
```

例えば、`{{PARTITION}}` の値として `aws` を指定できます。

[名前付き AWS 認証情報プロファイル](https://docs.aws.amazon.com/cli/v1/userguide/cli-configure-files.html#cli-configure-files-using-profiles)を使用する必要がある場合は、次のようにプロキシコマンドを変更します。

```
  ProxyCommand '/home/user/sagemaker_connect.sh' '%h' {{YOUR_CREDENTIAL_PROFILE_NAME}}
```
+ SSH 経由の接続または SCP コマンドを実行する場合:

```
ssh {{space-name}}
scp file_abc {{space-name}}:/tmp/
```

------
#### [ Windows ]

**Windows の前提条件:**
+ PowerShell 5.1 以降
+ SSH クライアント (OpenSSH を推奨)

PowerShell スクリプトを作成します (例: `C:\Users\{{user-name}}\sagemaker_connect.ps1`)。

```
# sagemaker_connect.ps1
param(
    [Parameter(Mandatory=$true)]
    [string]$SpaceArn,

    [Parameter(Mandatory=$false)]
    [string]$AwsProfile = ""
)

# Enable error handling
$ErrorActionPreference = "Stop"

# Validate ARN and extract region
if ($SpaceArn -match "^arn:aws[-a-z]*:sagemaker:([a-z0-9-]+):[0-9]{12}:space\/[^\/]+\/[^\/]+$") {
    $AwsRegion = $Matches[1]
} else {
    Write-Error "Error: Invalid SageMaker Studio Space ARN format."
    exit 1
}

# Build AWS CLI command
$awsCommand = @("sagemaker", "start-session", "--resource-identifier", $SpaceArn, "--region", $AwsRegion)

if ($AwsProfile) {
    $awsCommand += @("--profile", $AwsProfile)
}

try {
    # Start session and capture output
    Write-Host "Starting SageMaker session..." -ForegroundColor Green
    $startSessionOutput = & aws @awsCommand

    # Try to parse JSON response
    try {
        $sessionData = $startSessionOutput | ConvertFrom-Json
    } catch {
        Write-Error "Failed to parse JSON response: $_"
        Write-Host "Raw response was:" -ForegroundColor Yellow
        Write-Host $startSessionOutput
        exit 1
    }

    $sessionId = $sessionData.SessionId
    $streamUrl = $sessionData.StreamUrl
    $token = $sessionData.TokenValue

    # Validate extracted values
    if (-not $sessionId -or -not $streamUrl -or -not $token) {
        Write-Error "Error: Failed to extract session information from sagemaker start session response."
        Write-Host "Parsed response was:" -ForegroundColor Yellow
        Write-Host ($sessionData | ConvertTo-Json)
        exit 1
    }

    Write-Host "Session started successfully. Connecting..." -ForegroundColor Green

    # Create session manager plugin command
    $sessionJson = @{
        streamUrl = $streamUrl
        tokenValue = $token
        sessionId = $sessionId
    } | ConvertTo-Json -Compress

    # Escape the JSON string
    $escapedJson = $sessionJson -replace '"', '\"'

    # Call session-manager-plugin
    & session-manager-plugin "$escapedJson" $AwsRegion "StartSession"

} catch {
    Write-Error "Failed to start session: $_"
    exit 1
}
```
+ `C:\Users\{{user-name}}\.ssh\config` を設定して、以下のエントリを追加します。

```
Host {{space-name}}                            
  HostName "arn:aws:sagemaker:{{us-east-1}}:{{111122223333}}:space/{{domain-id}}/{{space-name}}"
  ProxyCommand "C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy RemoteSigned -File "C:\\Users\\{{user-name}}\\sagemaker_connect.ps1" "%h"
  ForwardAgent yes
  AddKeysToAgent yes
  User sagemaker-user
  StrictHostKeyChecking accept-new
```

------