1. 简介
Private Service Connect 接口是一种资源,允许提供方 Virtual Private Cloud (VPC) 网络发起与使用方网络中的各种目的地的连接。提供方网络与使用方网络可以位于不同的项目和组织中。
网络连接与 Private Service Connect 接口之间的连接类似于 Private Service Connect 端点与服务连接之间的连接,但存在以下两个主要区别:
- 网络连接允许提供方网络发起与使用方网络的连接(代管式服务出站流量),而端点则允许使用方网络发起与提供方网络的连接(代管式服务入站流量)。
- Private Service Connect 接口连接具有传递性。这意味着提供方网络可以与连接到使用方网络的其他网络通信。
构建内容
部署在 Google 托管的租户项目中的 Vertex AI Pipelines 将利用 PSC 网络连接在提供方网络和使用方网络之间创建多 NIC 实例。由于 PSC 网络附件是使用使用方网络中的多 NIC 部署的,因此 Vertex AI Pipelines 可以访问使用方网络中可用的路由。
在本教程中,您将为 Vertex AI Pipelines 构建一个全面的 Private Service Connect (PSC) 接口架构,该架构利用 Cloud 防火墙规则来允许或禁止从生产方到使用方的测试实例的连接,如图 1 所示。
图 1
您将在使用方 VPC 中创建一个 psc-network-attachment,从而实现以下用例:
- 在 consumer-vpc 中创建一个入站流量防火墙规则,允许 Vertex AI Pipeline 子网 (192.168.10.0/28) 访问 test-svc-1。使用 TCPDUMP 确认从流水线作业生成的 PING 成功发送到 test-svc-1
- 在 consumer-vpc 中创建一个入站防火墙规则,拒绝将 Vertex AI Pipelines 子网 (192.168.10.0/28) 授予 test-svc-2 访问权限。根据 Logs Explorer 生成的防火墙日志确认 PING 失败。
学习内容
- 如何创建网络连接
- Vertex AI Pipelines 如何使用网络附件创建 PSC 接口
- 如何建立生产者与使用方之间的通信
- 如何允许从 Vertex AI Pipelines 访问使用方虚拟机 test-svc-1
- 如何使用 Cloud Firewall 禁止 Vertex AI Pipelines 访问使用方虚拟机 test-svc-2
所需条件
- Google Cloud 项目
- IAM 权限
- Compute Instance Admin (roles/compute.instanceAdmin)
- Compute Network Admin (roles/compute.networkAdmin)
- Compute Security Admin (roles/compute.securityAdmin)
- IAP-secured Tunnel User (roles/iap.tunnelResourceAccessor)
- Logging Admin (roles/logging.admin)
- Notebooks 管理员 (roles/notebooks.admin)
- Project IAM Admin (roles/resourcemanager.projectIamAdmin)
- 配额管理员 (roles/servicemanagement.quotaAdmin)
- Service Account Admin (roles/iam.serviceAccountAdmin)
- Service Account User (roles/iam.serviceAccountUser)
- Vertex AI 管理员 (roles/aiplatform.admin)
2. 准备工作
本教程使用 $variables 来帮助在 Cloud Shell 中实现 gcloud 配置。
在 Cloud Shell 中,执行以下操作:
gcloud config list project
gcloud config set project [YOUR-PROJECT-NAME]
projectid=YOUR-PROJECT-NAME
echo $projectid
更新项目以支持本教程
在 Cloud Shell 中,执行以下操作:
gcloud services enable notebooks.googleapis.com
gcloud services enable aiplatform.googleapis.com
gcloud services enable compute.googleapis.com
gcloud services enable cloudresourcemanager.googleapis.com
3. 使用方设置
创建使用方 VPC
在 Cloud Shell 中,执行以下操作:
gcloud compute networks create consumer-vpc --project=$projectid --subnet-mode=custom
创建使用方子网
在 Cloud Shell 中,执行以下操作:
gcloud compute networks subnets create test-subnet-1 --project=$projectid --range=192.168.20.0/28 --network=consumer-vpc --region=us-central1
在 Cloud Shell 中,执行以下操作:
gcloud compute networks subnets create test-subnet-2 --project=$projectid --range=192.168.30.0/28 --network=consumer-vpc --region=us-central1
在 Cloud Shell 中,执行以下操作:
gcloud compute networks subnets create workbench-subnet --project=$projectid --range=192.168.40.0/28 --network=consumer-vpc --region=us-central1 --enable-private-ip-google-access
Cloud Router 和 NAT 配置
由于笔记本实例没有外部 IP 地址,因此本教程中使用了 Cloud 网络地址转换 (NAT) 来下载笔记本软件包。Cloud NAT 提供出站 NAT 功能,这意味着互联网主机不允许与用户管理的笔记本电脑发起通信,从而提高了安全性。
在 Cloud Shell 中,创建地区级 Cloud Router 路由器。
gcloud compute routers create cloud-router-us-central1 --network consumer-vpc --region us-central1
在 Cloud Shell 中,创建区域级 Cloud NAT 网关。
gcloud compute routers nats create cloud-nat-us-central1 --router=cloud-router-us-central1 --auto-allocate-nat-external-ips --nat-all-subnet-ip-ranges --region us-central1
创建 Private Service Connect 网络连接子网
在 Cloud Shell 中,创建 Vertex AI Pipelines 使用的网络附加子网。
gcloud compute networks subnets create intf-subnet --project=$projectid --range=192.168.10.0/28 --network=consumer-vpc --region=us-central1
4. 启用 Identity-Aware Proxy (IAP)
如需允许 IAP 连接到您的虚拟机实例,请创建一个防火墙规则,该规则:
- 适用于您希望使用 IAP 可访问的所有 VM 实例。
- 允许来自 IP 地址范围 35.235.240.0/20 的入站流量。此范围包含 IAP 用于 TCP 转发的所有 IP 地址。
在 Cloud Shell 中,创建 IAP 防火墙规则。
gcloud compute firewall-rules create ssh-iap-consumer \
--network consumer-vpc \
--allow tcp:22 \
--source-ranges=35.235.240.0/20
5. 创建使用方虚拟机实例
在 Cloud Shell 中,创建使用方虚拟机实例 test-svc-1。
gcloud compute instances create test-svc-1 \
--project=$projectid \
--machine-type=e2-micro \
--image-family debian-11 \
--no-address \
--image-project debian-cloud \
--zone us-central1-a \
--subnet=test-subnet-1 \
--shielded-secure-boot
在 Cloud Shell 中,创建使用方虚拟机实例 test-svc-2。
gcloud compute instances create test-svc-2 \
--project=$projectid \
--machine-type=e2-micro \
--image-family debian-11 \
--no-address \
--image-project debian-cloud \
--zone us-central1-a \
--subnet=test-subnet-2 \
--shielded-secure-boot
获取并存储实例的 IP 地址:
在 Cloud Shell 中,针对测试虚拟机实例执行 describe 操作。
gcloud compute instances describe test-svc-1 --zone=us-central1-a | grep networkIP:
gcloud compute instances describe test-svc-2 --zone=us-central1-a | grep networkIP:
示例:
user@cloudshell(psc-vertex)$ gcloud compute instances describe test-svc-1 --zone=us-central1-a | grep networkIP:
gcloud compute instances describe test-svc-2 --zone=us-central1-a | grep networkIP:
networkIP: 192.168.20.2
networkIP: 192.168.30.2
6. Private Service Connect 网络连接
网络连接是区域级资源,表示 Private Service Connect 接口的使用方端。您将单个子网与一个网络连接关联,而提供方(Vertex AI 渠道)将 IP 分配给 Private Service Connect 接口。
创建网络连接
在 Cloud Shell 中,创建网络连接。
gcloud compute network-attachments create psc-network-attachment \
--region=us-central1 \
--connection-preference=ACCEPT_MANUAL \
--subnets=intf-subnet
列出网络连接
在 Cloud Shell 中,列出网络连接。
gcloud compute network-attachments list
描述网络连接
在 Cloud Shell 中,描述网络连接。
gcloud compute network-attachments describe psc-network-attachment --region=us-central1
记下提供方在创建 Private Service Connect 接口时将使用的 psc-network-attachment URI。
在以下示例中,psc 网络附加 URI 如下所示:
projects/psc-vertex/regions/us-central1/networkAttachments/psc-network-attachment
user@cloudshell$ gcloud compute network-attachments describe psc-network-attachment --region=us-central1
connectionPreference: ACCEPT_MANUAL
creationTimestamp: '2025-01-21T12:25:25.385-08:00'
fingerprint: m9bHc9qnosY=
id: '56224423547354202'
kind: compute#networkAttachment
name: psc-network-attachment
network: https://www.googleapis.com/compute/v1/projects/psc-vertex/global/networks/consumer-vpc
region: https://www.googleapis.com/compute/v1/projects/psc-vertex/regions/us-central1
selfLink: https://www.googleapis.com/compute/v1/projects/psc-vertex/regions/us-central1/networkAttachments/psc-network-attachment
subnetworks:
- https://www.googleapis.com/compute/v1/projects/psc-vertex/regions/us-central1/subnetworks/intf-subnet
7. Vertex AI Workbench 设置
以下部分将指导您创建 Jupyter 笔记本。此笔记本将用于部署一个 Pipelines 作业,该作业会从 Vertex AI Pipelines 向测试实例发送 PING。Vertex AI Pipelines 与包含实例的使用方网络之间的数据路径使用 Private Service Connect 网络接口。
创建用户管理的服务账号
在下一部分中,您将创建一个服务账号,该服务账号将与本教程中使用的 Vertex AI Workbench 实例相关联。
在本教程中,系统会为服务账号应用以下角色:
在 Cloud Shell 中,创建服务账号。
gcloud iam service-accounts create notebook-sa \
--display-name="notebook-sa"
在 Cloud Shell 中,为服务账号分配“Storage Admin”角色。
gcloud projects add-iam-policy-binding $projectid --member="serviceAccount:notebook-sa@$projectid.iam.gserviceaccount.com" --role="roles/storage.admin"
在 Cloud Shell 中,使用 Vertex AI User 角色更新服务账号。
gcloud projects add-iam-policy-binding $projectid --member="serviceAccount:notebook-sa@$projectid.iam.gserviceaccount.com" --role="roles/aiplatform.user"
在 Cloud Shell 中,为服务账号授予 Artifact Registry Admin 角色。
gcloud projects add-iam-policy-binding $projectid --member="serviceAccount:notebook-sa@$projectid.iam.gserviceaccount.com" --role="roles/artifactregistry.admin"
在 Cloud Shell 中,允许该 Notebook 服务账号使用 Compute Engine 默认服务账号实例化流水线作业。
gcloud iam service-accounts add-iam-policy-binding \
$(gcloud projects describe $(gcloud config get-value project) --format='value(projectNumber)')-compute@developer.gserviceaccount.com \
--member="serviceAccount:notebook-sa@$projectid.iam.gserviceaccount.com" \
--role="roles/iam.serviceAccountUser"
创建 Vertex AI Workbench 实例
在下一部分中,创建一个包含之前创建的服务账号 notebook-sa 的 Vertex AI Workbench 实例。
在 Cloud Shell 中,创建专用客户端实例。
gcloud workbench instances create workbench-tutorial --vm-image-project=deeplearning-platform-release --vm-image-family=common-cpu-notebooks --machine-type=n1-standard-4 --location=us-central1-a --subnet-region=us-central1 --subnet=workbench-subnet --disable-public-ip --shielded-secure-boot=true --service-account-email=notebook-sa@$projectid.iam.gserviceaccount.com
8. Vertex AI Pipelines 与 test-svc-1 的连接
打开新的 Cloud Shell 标签页,然后更新您的项目设置。
在 Cloud Shell 中,执行以下操作:
gcloud config list project
gcloud config set project [YOUR-PROJECT-NAME]
projectid=YOUR-PROJECT-NAME
echo $projectid
如需允许 Vertex AI 流水线与 test-svc-1 建立连接,请创建入站防火墙规则,将 PSC 网络附件指定为来源 (192.168.10.0/28),并将 test-svc-1 IP 地址指定为目的地。
在 Cloud Shell 中,更新 destination-range 以匹配 test-svc-1 IP 地址。
gcloud compute --project=$projectid firewall-rules create allow-icmp-vertex-pipelines-to-test-svc1-vm --direction=INGRESS --priority=1000 --network=consumer-vpc --action=ALLOW --source-ranges=192.168.10.0/28 --destination-ranges=<your-test-svc-1-vm-ip> --rules=icmp
示例:
gcloud compute --project=$projectid firewall-rules create allow-icmp-vertex-pipelines-to-test-svc1-vm --direction=INGRESS --priority=1000 --network=consumer-vpc --action=ALLOW --source-ranges=192.168.10.0/28 --destination-ranges=192.168.20.2 --rules=icmp
在 Cloud Shell 中使用 IAP 登录 test-svc-1 实例。
gcloud compute ssh test-svc-1 --project=$projectid --zone=us-central1-a --tunnel-through-iap
在操作系统中,执行 tcpdump 以捕获任何 icmp 流量。此操作系统会话将用于验证 Vertex AI Pipelines 与虚拟机之间的通信。
sudo tcpdump -i any icmp -nn
9. Vertex AI Service Agent 更新
Vertex AI Pipelines 会代表您执行操作,例如从用于创建 PSC 接口的 PSC 网络连接子网获取 IP 地址。为此,Vertex AI Pipelines 使用需要 Network Admin 权限的服务代理(如下所列)。
service-$projectnumber@gcp-sa-aiplatform.iam.gserviceaccount.com
在 Cloud Shell 中,获取您的项目编号。
gcloud projects describe $projectid | grep projectNumber
示例:
gcloud projects describe $projectid | grep projectNumber:
projectNumber: '795057945528'
在 Cloud Shell 中,为服务代理账号授予 compute.networkAdmin 角色。
gcloud projects add-iam-policy-binding $projectid --member="serviceAccount:service-<your-projectnumber>@gcp-sa-aiplatform.iam.gserviceaccount.com" --role="roles/compute.networkAdmin"
示例:
gcloud projects add-iam-policy-binding $projectid --member="serviceAccount:service-795057945528@gcp-sa-aiplatform.iam.gserviceaccount.com" --role="roles/compute.networkAdmin"
10. 默认服务账号更新
启用 Compute Engine API 并向您的默认服务账号授予对 Vertex AI 的访问权限。请注意,访问权限更改可能需要一段时间才能传播。
在 Cloud Shell 中,使用角色 aiplatform.user 更新默认服务账号
gcloud projects add-iam-policy-binding $projectid \
--member="serviceAccount:<your-projectnumber>-compute@developer.gserviceaccount.com" \
--role="roles/aiplatform.user"
示例:
gcloud projects add-iam-policy-binding $projectid \
--member="serviceAccount:795057945528-compute@developer.gserviceaccount.com" \
--role="roles/aiplatform.user"
11. 部署 Vertex AI Pipelines 作业
在下一部分中,您将创建一个笔记本,以成功向使用方 test-svc-1 实例执行 PING 操作。
在 Vertex AI Workbench 实例中运行训练作业。
- 在 Google Cloud 控制台中,前往 Vertex AI Workbench 页面上的“实例”标签页。
- 在 Vertex AI Workbench 实例名称 (workbench-tutorial) 旁边,点击“打开 JupyterLab”。您的 Vertex AI Workbench 实例会打开 JupyterLab。
- 依次选择“文件”>“新建”>“笔记本”
- 依次选择“Kernel”>“Python 3”
- 在新的笔记本单元格中,运行以下命令,确保您拥有最新版本的 pip:
! pip3 install --upgrade --quiet google-cloud-aiplatform \
kfp \
google-cloud-pipeline-components
- 在新建的笔记本单元格中设置项目变量
PROJECT_ID = "<your-projectid>"
REGION = "<your-region>"
NETWORK_ATTACHMENT_NAME = "psc-network-attachment"
示例:
PROJECT_ID = "psc-vertex"
REGION = "us-central1"
NETWORK_ATTACHMENT_NAME = "psc-network-attachment"
- 在新的笔记本单元格中将全局唯一的存储分区名称定义为变量
BUCKET_URI = f"gs://<your-bucket-name>"
示例:
BUCKET_URI = f"gs://psc-vertex-bucket"
- 在新的笔记本单元中,创建存储分区
! gsutil mb -l {REGION} -p {PROJECT_ID} {BUCKET_URI}
在下一部分中,您将确定用于运行流水线作业的默认 Compute Engine 服务账号,并向其授予正确的权限。
shell_output = ! gcloud projects describe $PROJECT_ID
PROJECT_NUMBER = shell_output[-1].split(":")[1].strip().replace("'", "")
SERVICE_ACCOUNT = f"{PROJECT_NUMBER}-compute@developer.gserviceaccount.com"
print(f"Project Number: {PROJECT_NUMBER}")
print(f"Service Account: {SERVICE_ACCOUNT}")
为确认执行成功,系统会输出您的服务账号和项目编号
- 在新建的记事单单元格中,向您的服务账号授予读写在上一步创建的存储分区中的流水线工件的权限。
! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator {BUCKET_URI}
! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer {BUCKET_URI}
- 在新的笔记本单元中,定义流水线参数。请注意,NETWORK_ATTACHMENT_NAME 是 PSC 网络附件,因此必须匹配。
PIPELINE_ROOT = f"{BUCKET_URI}/pipeline_root/psc_test"
NETWORK_ATTACHMENT_URI = f"projects/{PROJECT_NUMBER}/regions/{REGION}/networkAttachments/{NETWORK_ATTACHMENT_NAME}"
- 在新建的笔记本单元格中,初始化 Vertex AI SDK
from kfp import dsl
from google.cloud import aiplatform, aiplatform_v1beta1
import time
from google.cloud.aiplatform_v1.types import pipeline_state
import yaml
from datetime import datetime
import logging
aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
- 在新的笔记本单元中,定义测试组件
@dsl.container_component
def ping_check(network_address: str):
"""Pings a network address
Args:
network_address: The IP address to ping
"""
return dsl.ContainerSpec(
image="ubuntu:22.04",
command=["sh", "-c"],
args=[
f"""
# Use sed for regex replacement, cleaner than bash parameter expansion for this
cleaned_address=$(echo "{network_address}" | sed 's/[^0-9.]//g')
apt-get update && apt-get install inetutils-traceroute inetutils-ping -y
echo "Will ping $cleaned_address"
if ! ping -c 3 $cleaned_address; then
echo "Ping failed"
traceroute -w 1 -m 7 $cleaned_address
exit 1
fi
"""
],
)
- 在新的笔记本单元中,定义流水线
@dsl.pipeline(name="check-connectivity")
def pipeline(ip_address: str):
"""Pings an IP address. Facilitated by a Private Service Connect Interface
Args:
ip_address: The IP address to ping
"""
ping_check(network_address=ip_address).set_caching_options(False)
return
- 在新的笔记本单元格中,执行实用程序函数,等待流水线完成
def wait_for_pipeline(
project_id: str,
region: str,
pipeline_job_resource_name: str,
timeout: int = 20 * 60, # Default timeout of 20 minutes (in seconds)
) -> bool:
"""
Waits for a Vertex AI pipeline to finish, with a timeout.
Args:
project_id (str): The Google Cloud project ID.
region (str): The region where the pipeline is running.
pipeline_job_resource_name (str): The resource name of the pipeline job.
timeout (int): The maximum time to wait for the pipeline to finish, in seconds.
Defaults to 20 minutes (1200 seconds).
Returns:
bool: True if the pipeline succeeded, False otherwise.
Raises:
TimeoutError: If the pipeline does not finish within the specified timeout.
"""
# Initialize the AIPlatform client
aiplatform.init(project=project_id, location=region)
# Get the pipeline job
pipeline_job = aiplatform.PipelineJob.get(resource_name=pipeline_job_resource_name)
logging.info(
f"Vertex AI Console Link: https://console.cloud.google.com/vertex-ai/pipelines/locations/{region}/runs/{pipeline_job.resource_name.split('/')[-1]}?project={project_id}"
)
start_time = time.time()
while True:
status = pipeline_job.state
logging.info(f"Pipeline Job status: {status.name}")
if status in [
pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
pipeline_state.PipelineState.PIPELINE_STATE_FAILED,
pipeline_state.PipelineState.PIPELINE_STATE_CANCELLED,
]:
break # Exit the loop if the job is finished
if time.time() - start_time > timeout:
logging.error(f"Pipeline timed out after {timeout} seconds.")
raise TimeoutError(f"Pipeline timed out after {timeout} seconds.")
# Wait for a short time before checking again
time.sleep(10) # Adjust the wait time as needed
# Do something based on the final status
if status == pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED:
logging.info("Pipeline succeeded")
return True
elif status == pipeline_state.PipelineState.PIPELINE_STATE_CANCELLED:
logging.error("Pipeline cancelled")
raise Exception("Pipeline cancelled")
elif status == pipeline_state.PipelineState.PIPELINE_STATE_FAILED:
logging.error("Pipeline failed")
raise Exception("Pipeline failed")
- 在新的笔记本单元格中,执行实用程序函数以运行流水线
def run_job_with_psc_interface_config(
project_id: str,
region: str,
pipeline_root: str,
network_attachment_name: str,
ip_address: str,
local_pipeline_file: str = "pipeline.yaml",
):
"""
Compiles, submits, and monitors a Vertex AI pipeline.
"""
parameter_values = {"ip_address": ip_address}
pipeline_root = f"{pipeline_root}/{datetime.now().strftime('%Y%m%d%H%M%S')}"
logging.info("Compiling pipeline")
try:
with open(local_pipeline_file, "r") as stream:
pipeline_spec = yaml.safe_load(stream)
logging.info(f"Pipeline Spec: {pipeline_spec}")
except yaml.YAMLError as exc:
logging.error(f"Error loading pipeline yaml file: {exc}")
raise
logging.info(f"Will use pipeline root: {pipeline_root}")
# Initialize the Vertex SDK using PROJECT_ID and LOCATION
aiplatform.init(project=project_id, location=region)
# Create the API endpoint
client_options = {"api_endpoint": f"{region}-aiplatform.googleapis.com"}
# Initialize the PipelineServiceClient
client = aiplatform_v1beta1.PipelineServiceClient(client_options=client_options)
# Construct the request
request = aiplatform_v1beta1.CreatePipelineJobRequest(
parent=f"projects/{project_id}/locations/{region}",
pipeline_job=aiplatform_v1beta1.PipelineJob(
display_name="pipeline-with-psc-interface-config",
pipeline_spec=pipeline_spec,
runtime_config=aiplatform_v1beta1.PipelineJob.RuntimeConfig(
gcs_output_directory=pipeline_root, parameter_values=parameter_values
),
psc_interface_config=aiplatform_v1beta1.PscInterfaceConfig(
network_attachment=network_attachment_name
),
),
)
# Make the API call
response = client.create_pipeline_job(request=request)
# Print the response
logging.info(f"Pipeline job created: {response.name}")
return response.name
- 在新的笔记本单元中,编译流水线
from kfp import compiler
compiler.Compiler().compile(pipeline_func=pipeline, package_path='pipeline.yaml')
- 在新的工作簿单元格中,更新 TARGET_IP_ADDRESS,以反映在上一步中为 test-svc-1 获取的 IP 地址,并观察流水线作业状态
TARGET_IP_ADDRESS = "<your-test-svc-1-ip>"
try:
job_name = run_job_with_psc_interface_config(
project_id=PROJECT_ID,
region=REGION,
pipeline_root=PIPELINE_ROOT,
network_attachment_name=NETWORK_ATTACHMENT_URI,
ip_address=TARGET_IP_ADDRESS,
)
wait_for_pipeline(
project_id=PROJECT_ID,
region=REGION,
pipeline_job_resource_name=job_name,
)
except Exception as e:
logging.error(f"An error occurred: {e}")
示例:
TARGET_IP_ADDRESS = "192.168.20.2"
try:
job_name = run_job_with_psc_interface_config(
project_id=PROJECT_ID,
region=REGION,
pipeline_root=PIPELINE_ROOT,
network_attachment_name=NETWORK_ATTACHMENT_URI,
ip_address=TARGET_IP_ADDRESS,
)
wait_for_pipeline(
project_id=PROJECT_ID,
region=REGION,
pipeline_job_resource_name=job_name,
)
except Exception as e:
logging.error(f"An error occurred: {e}")
执行第 17 步后,流水线将需要大约 8 分钟才能完成。
12. 验证与 test-svc-1 的连接
在用于执行第 17 步的单元格中,观察流水线作业状态从 PIPELINE_STATE_PENDING 转换为 PIPELINE_STATE_RUNNING,最终转换为 PIPELINE_STATE_SUCCEEDED,这表示 Vertex AI Pipelines 成功执行了 ping 操作,并收到了来自 test-svc-1 的响应。
如需验证 Vertex AI Pipelines 和 test-svc-1 之间的 ICMP 流量,请查看在 test-svc-1 OS 中执行的之前生成的 tcpdump 会话,该会话会提供指示双向流量的日志。
在 tcpdump 示例中,Vertex AI 渠道从 192.168.10.0/28 子网中获取了 IP 地址 192.168.10.3,192.168.20.2 是 test-svc-1 的 IP 地址。请注意,在您的环境中,IP 地址可能会有所不同。
user@test-svc-1:~$ sudo tcpdump -i any icmp -nn
tcpdump: data link type LINUX_SLL2
tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
listening on any, link-type LINUX_SLL2 (Linux cooked v2), snapshot length 262144 bytes
18:57:54.737490 ens4 In IP 192.168.10.3 > 192.168.20.2: ICMP echo request, id 257, seq 0, length 64
18:57:54.737523 ens4 Out IP 192.168.20.2 > 192.168.10.3: ICMP echo reply, id 257, seq 0, length 64
13. Vertex AI Pipelines AI 与 test-svc-2 的连接
在下一部分中,您将创建一条入站防火墙规则,以拒绝来自 Vertex AI Pipelines 子网 (192.168.10.0/28) 的流量传入 test-svc-2,然后更新 Notebook 以反映 test-svc-2 IP 地址,最后执行 Pipelines 作业运行。
在 Notebook 单元格中,流水线作业状态将显示“Error - Pipeline Failed”(错误 - 流水线失败),此外,防火墙日志记录将提供有关连接失败的分析信息。
创建拒绝入站流量的防火墙规则
如需禁止 Vertex AI 流水线与 test-svc-2 之间的连接,请创建入站防火墙规则,将 PSC 网络附件指定为来源 (192.168.10.0/28),并将 test-svc-2 IP 地址指定为目的地。
在 Cloud Shell 中,更新 destination-range 以与 test-svc-2 IP 地址匹配。
gcloud compute --project=$projectid firewall-rules create deny-icmp-vertex-pipelines-to-test-svc2-vm --direction=INGRESS --priority=1000 --network=consumer-vpc --action=DENY --source-ranges=192.168.10.0/28 --rules=ALL --destination-ranges=<your-test-svc-2-vm-ip> --rules=icmp --enable-logging
示例:
gcloud compute --project=$projectid firewall-rules create deny-icmp-vertex-pipelines-to-test-svc2-vm --direction=INGRESS --priority=1000 --network=consumer-vpc --action=DENY --source-ranges=192.168.10.0/28 --rules=ALL --destination-ranges=192.168.30.2 --enable-logging
从笔记本单元格执行流水线作业
在新的工作簿单元格中,更新 TARGET_IP_ADDRESS,以反映上一步中为 test-svc-2 获取的 IP 地址,然后观察流水线作业状态。
TARGET_IP_ADDRESS = "<your-test-svc-2-ip>"
try:
job_name = run_job_with_psc_interface_config(
project_id=PROJECT_ID,
region=REGION,
pipeline_root=PIPELINE_ROOT,
network_attachment_name=NETWORK_ATTACHMENT_URI,
ip_address=TARGET_IP_ADDRESS,
)
wait_for_pipeline(
project_id=PROJECT_ID,
region=REGION,
pipeline_job_resource_name=job_name,
)
except Exception as e:
logging.error(f"An error occurred: {e}")
示例:
TARGET_IP_ADDRESS = "192.168.30.2"
try:
job_name = run_job_with_psc_interface_config(
project_id=PROJECT_ID,
region=REGION,
pipeline_root=PIPELINE_ROOT,
network_attachment_name=NETWORK_ATTACHMENT_URI,
ip_address=TARGET_IP_ADDRESS,
)
wait_for_pipeline(
project_id=PROJECT_ID,
region=REGION,
pipeline_job_resource_name=job_name,
)
except Exception as e:
logging.error(f"An error occurred: {e}")
流水线作业在执行后大约需要 8 分钟才能完成。
14. 验证与 test-svc-2 的连接失败
在用于执行 Pipelines 作业的单元格中,请注意状态从 PIPELINE_STATE_PENDING 转换为 PIPELINE_STATE_FAILED,这表示 Vertex AI Pipelines 的 ping 失败,并且 test-svc-2 没有响应。
您可以使用日志浏览器查看与入站拒绝规则(包含 Vertex AI Pipelines 子网 [192.168.10.0/28] 和 test-svc-2 IP 地址)匹配的防火墙日志记录条目。
选择“显示查询”,然后在下方插入过滤条件“过去 15 分钟”,接着点击“运行查询”。
jsonPayload.rule_details.reference:("network:consumer-vpc/firewall:deny-icmp-vertex-pipelines-to-test-svc2-vm")
选择一个日志条目,然后展开嵌套字段,以显示包含 Vertex AI Pipelines 和 test-svc-2 IP 地址的信息元素,用于验证被拒绝的入站防火墙规则。
15. 清理
在 Cloud Shell 中,删除教程组件。
gcloud compute instances delete test-svc-1 test-svc-2 --zone=us-central1-a --quiet
gcloud workbench instances delete workbench-tutorial --location=us-central1-a --quiet
gcloud compute firewall-rules delete deny-icmp-vertex-pipelines-to-test-svc2-vm allow-icmp-vertex-pipelines-to-test-svc1-vm ssh-iap-consumer --quiet
gcloud compute routers nats delete cloud-nat-us-central1 --router=cloud-router-us-central1 --region us-central1 --quiet
gcloud compute routers delete cloud-router-us-central1 --region=us-central1 --quiet
16. 恭喜
恭喜,您已成功通过实现入站流量允许和拒绝防火墙,配置并验证了 Private Service Connect 接口以及使用方和提供方的连接。
您已创建使用方基础架构,并添加了网络连接,以允许 Vertex AI Pipelines 服务创建 PSC 接口虚拟机,以桥接使用方与提供方之间的通信。您学习了如何在使用方 VPC 网络中创建防火墙规则,以允许和拒绝与使用方网络中的实例建立连接。
Cosmopup 认为教程很棒!