

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 设置本地 Visual Studio Code


管理员完成中的说明后[通过远程访问将您的本地 Visual Studio 代码连接到 SageMaker 空间](remote-access.md)，您可以将本地 Visual Studio 代码连接到远程 SageMaker 空间。

**Topics**
+ [

## 设置本地环境
](#remote-access-local-ide-setup-local-environment)
+ [

## 连接到本地 VS Code
](#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)

## 设置本地环境


在本地计算机上安装 [Visual Studio Code](https://code.visualstudio.com/)。有关要求的信息，请参阅[通过远程访问将您的本地 Visual Studio 代码连接到 SageMaker 空间](remote-access.md)。

## 连接到本地 VS Code


在建立从本地 Visual Studio Code 到远程 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： Amazon Toolkit for Visual Studio Code
](#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 的深度链接


执行以下过程，使用深度链接建立连接。

1. [启动 Amazon SageMaker Studio](https://docs.amazonaws.cn/sagemaker/latest/dg/studio-updated-launch.html#studio-updated-launch-console)。

1. 在 Studio UI 中，导航到您的空间。

1. 选择**空间打开方式**。

1. 选择 **VS Code**。在执行此操作时，系统可能会提示您**打开 Visual Studio Code**。当您选择执行此操作时，您的本地 VS Code 将打开，并弹出另一个确认窗口。完成后，远程连接即已建立。

### 方法 2： Amazon Toolkit for Visual Studio Code


执行以下过程，使用 Amazon Toolkit for Visual Studio Code建立连接。

1. 打开 VS Code。

1. 打开 Amazon 工具包扩展。

1. [连接到 Amazon](https://docs.amazonaws.cn/toolkit-for-vscode/latest/userguide/connect.html)。

1. 在 Amazon 资源管理器中，展开 **SageMaker AI**。

1. 找到您的 Studio 空间。

1. 选择该空间旁边的**连接**图标即可将其启动。
**注意**  
停止并重新启动 Toolkit for Visual Studio 中的空间以启用远程访问（如果尚未连接）。
如果空间未使用支持的[实例大小](https://docs.amazonaws.cn/sagemaker/latest/dg/remote-access.html#remote-access-instance-requirements)，系统将要求您更改实例。

### 方法 3：通过 SSH CLI 从终端连接


选择以下平台选项之一，查看使用 SSH CLI 建立连接的过程。

**注意**  
在按照以下说明进行操作之前，请确保[本地计算机先决条件](remote-access.md#remote-access-local-prerequisites)已安装最新版本。
如果是[自带映像（BYOI）](studio-updated-byoi.md)，请确保已安装中列出的必需依赖项，[映像要求](remote-access.md#remote-access-image-requirements)然后再继续

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

创建一个 Shell 脚本（例如 `/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`。

如果您需要使用已[命名的 Amazon 凭据配置文件](https://docs.amazonaws.cn/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 Amazon 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
```

------

# 连接到具有无互联网访问权限的子网的 VPC
连接到无互联网访问权限的私有子网

在将 Visual Studio Code 连接到无互联网访问权限的私有子网中的 Studio 空间之前，请确保您的管理员已[将 Studio 设置为在 VPC 中使用无互联网访问权限的子网运行](remote-access-remote-setup-vpc-subnets-without-internet-access.md)。

您可以通过两种方式将本地 Visual Studio Code 连接到私有子网中的 Studio 空间：
+ 设置 HTTP 代理
+ 预打包的 VS Code 远程服务器和扩展

**Topics**
+ [

## 带受控允许列表的 HTTP 代理
](#remote-access-local-ide-setup-vpc-no-internet-http-proxy-with-controlled-allow-listing)
+ [

## 预打包的 VS Code 远程服务器和扩展
](#remote-access-local-ide-setup-vpc-no-internet-pre-packaged-vs-code-remote-server-and-extensions)

## 带受控允许列表的 HTTP 代理


当您的 Studio 空间位于防火墙或代理后面时，请要求您的管理员允许访问 VS Code 服务器 CDNs 以及与扩展相关的端点。有关更多信息，请参阅 [设置带受控允许列表的 HTTP 代理](remote-access-remote-setup-vpc-subnets-without-internet-access.md#remote-access-remote-setup-vpc-subnets-without-internet-access-setup-http-proxy-with-controlled-allow-listing)。

设置完成后，您可以通过提供代理 URL 与 `remote.SSH.httpProxy` 或 `remote.SSH.httpsProxy` 设置，为 VS Code 远程开发配置 HTTP 代理。

**注意**  
考虑启用“Remote.SSH：使用 Curl 和 Wget 配置文件”，以使用远程环境的 `curlrc` 和 `wgetrc` 文件中的配置。这样，放置在 SageMaker 空间中各自默认位置的`curlrc`和`wgetrc`文件就可以用来启用某些案例。

此选项在您有权设置 HTTP 代理时适用，并可让您灵活地安装其他扩展，因为某些扩展需要公共端点。

## 预打包的 VS Code 远程服务器和扩展


当 Studio 空间无法访问外部端点以下载 VS Code 远程服务器和扩展时，可以将其预打包。通过这种方法，您的管理员可以导出一个压缩包，其中包含特定版本的 VS Code 的 `.VS Code-server` 目录。然后，管理员使用 A SageMaker I 生命周期配置 (LCC) 脚本将压缩包复制并解压缩到您的主目录 (`/home/sagemaker-user`)。有关更多信息，请参阅 [设置预打包的 Visual Studio Code 远程服务器和扩展](remote-access-remote-setup-vpc-subnets-without-internet-access.md#remote-access-remote-setup-vpc-subnets-without-internet-access-setup-pre-packaged-vs-code-remote-server-and-extensions)。

**VS Code 远程服务器和扩展的预打包说明**

1. 在本地计算机上安装 VS Code

1. 当您连接到 SageMaker 空间时：
   + 使用默认配置文件以确保与预打包扩展的兼容性。否则，您需要在连接到 Studio 空间后，使用下载的 VSIX 文件安装扩展。
   + 选择要在启动空间时附加到空间的特定于 VS Code 版本的 LCC 脚本。

### 用于预打包 VS Code 远程服务器和扩展的 Dockerfile 用法示例


以下是一个示例 Dockerfile，用于在无法创建已启用远程访问和互联网连接的空间时，启动预安装了 SSH 服务器的本地容器。

**注意**  
在此示例中，SSH 服务器不需要身份验证，并且仅用于导出 VS Code 远程服务器。
应在 x64 架构上构建和运行容器。

```
FROM amazonlinux:2023

# Install OpenSSH server and required tools
RUN dnf install -y \
    openssh-server \
    shadow-utils \
    passwd \
    sudo \
    tar \
    gzip \
    && dnf clean all

# Create a user with no password
RUN useradd -m -s /bin/bash sagemaker-user && \
    passwd -d sagemaker-user

# Add sagemaker-user to sudoers via wheel group
RUN usermod -aG wheel sagemaker-user && \
    echo 'sagemaker-user ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/sagemaker-user && \
    chmod 440 /etc/sudoers.d/sagemaker-user

# Configure SSH to allow empty passwords and password auth
RUN sed -i 's/^#\?PermitEmptyPasswords .*/PermitEmptyPasswords yes/' /etc/ssh/sshd_config && \
    sed -i 's/^#\?PasswordAuthentication .*/PasswordAuthentication yes/' /etc/ssh/sshd_config

# Generate SSH host keys
RUN ssh-keygen -A

# Expose SSH port
EXPOSE 22

WORKDIR /home/sagemaker-user
USER sagemaker-user

# Start SSH server
CMD ["bash"]
```

使用以下命令可构建和运行容器：

```
# Build the image
docker build . -t remote_server_export

# Run the container
docker run --rm -it -d \
  -v /tmp/remote_access/.VS Code-server:/home/sagemaker-user/.VS Code-server \
  -p 2222:22 \
  --name remote_server_export \
  remote_server_export
  
# change the permisson for the mounted folder
docker exec -i remote_server_export \
       bash -c 'sudo chown sagemaker-user:sagemaker-user ~/.VS Code-server'

# start the ssh server in the container 
docker exec -i remote_server_export bash -c 'sudo /usr/sbin/sshd -D &'
```

使用以下命令进行连接：

```
ssh sagemaker-user@localhost -p 2222
```

必须先在 `.ssh/config` 文件中配置以下内容，之后才能连接此容器。之后，在进行连接时，您将能够在远程 SSH 侧面板中看到 `remote_access_export` 作为主机名。例如：

```
Host remote_access_export
  HostName localhost
  User=sagemaker-user
  Port 2222
  ForwardAgent yes
```

归档 `/tmp/remote_access/.VS Code-server`，并执行“预打包的 VS Code 远程服务器和扩展”中的步骤，以连接和安装扩展。解压缩后，确保 `.VS Code-server` 文件夹显示为父文件夹。

```
cd /tmp/remote_access/
sudo tar -czvf VS Code-server-with-extensions-for-1.100.2.tar.gz .VS Code-server
```

### LCC 脚本示例 (LCC-install-VS C ode-server-v 1.100.2)


以下示例说明如何安装特定版本的 VS Code 远程服务器。

```
#!/bin/bash

set -x

remote_server_file=VS Code-server-with-extensions-for-1.100.2.tar.gz

if [ ! -d "${HOME}/.VS Code-server" ]; then
    cd /tmp
    aws s3 cp s3://S3_BUCKET/remote_access/${remote_server_file} .
    tar -xzvf ${remote_server_file}
    mv .VS Code-server "${HOME}"
    rm ${remote_server_file}
else
    echo "${HOME}/.VS Code-server already exists, skipping download and install."
fi
```

# 筛选您的 Studio 空间


您可以使用筛选功能在 Amazon Toolkit for Visual Studio Code 资源管理器中仅显示相关的 SageMaker Amazon AI 空间。下文提供了有关手动筛选和自动筛选的信息。有关手动筛选和自动筛选的定义的更多信息，请参阅[筛选概述](remote-access-remote-setup-filter.md#remote-access-remote-setup-filter-overview)。

仅当使用该[方法 2： Amazon Toolkit for Visual Studio Code](remote-access-local-ide-setup.md#remote-access-local-ide-setup-local-vs-code-method-2-aws-toolkit-in-vs-code)方法从本地 Visual Studio 代码连接到 Amazon SageMaker Studio 空间时，此设置才适用。请参阅[设置远程访问](remote-access-remote-setup.md)了解更多信息。

**Topics**
+ [

## 手动筛选
](#remote-access-local-ide-setup-filter-manual)
+ [

## 使用 IAM 凭证登录时的自动筛选设置
](#remote-access-local-ide-setup-filter-automatic-IAM-credentials)

## 手动筛选


要手动筛选显示的空间，请执行以下操作：
+ 打开 VS Code，并导航到 Toolkit for VS Code 侧面板资源管理器
+ 找到 A **SageMaker I** 专区
+ 选择 A SageMaker I 部分标题右侧的过滤器图标。这将打开一个下拉菜单。
+ 在该下拉菜单中，选择要为其显示空间的用户配置文件

## 使用 IAM 凭证登录时的自动筛选设置


自动筛选取决于登录期间使用的身份验证方法。有关更多信息[，请参阅《VS Code 工具包用户指南》中的 “ Amazon 从工具包连接](https://docs.amazonaws.cn/toolkit-for-vscode/latest/userguide/connect.html#connect-to-aws)”。

在使用 **IAM 凭证**进行身份验证和连接时，自动筛选需要[使用 IAM 凭证进行连接时设置](remote-access-remote-setup-filter.md#remote-access-remote-setup-filter-set-up-iam-credentials)。如果未进行此设置，当用户选择启用身份筛选时，将不会显示任何空间。

上述设置完成后， Amazon Toolkit 会匹配属于以经过身份验证的 IAM 用户名或代入角色会话名称开头的用户配置文件的空格。

用户需选择启用自动筛选：
+ 打开 VS Code 设置
+ 导航到 **Amazon Toolkit** 扩展
+ 查找**启用身份筛选**
+ 选择根据您的 Amazon 身份启用空间自动筛选