1. 簡介
Private Service Connect 介面是一種資源,可讓供應商虛擬私有雲 (VPC) 網路啟動至用戶端網路中的各種目的地連線。供應商網路和消費者網路可以位於不同的專案和機構。
網路附件和 Private Service Connect 介面之間的連線類似於 Private Service Connect 端點和服務附件之間的連線,但有兩個主要差異:
- 網路連結可讓供應商網路啟動與消費者網路的連線 (受管理的服務輸出),而端點則可讓消費者網路啟動與供應商網路的連線 (受管理的服務輸入)。
- Private Service Connect 介面連線是傳遞式連線。也就是說,供應端網路可以與連線至消費者網路的其他網路通訊。
建構項目
在 Google 管理的租用戶專案中部署的 Vertex AI Pipelines 會利用 PSC 網路附件,在生產端網路和消費者網路之間建立多個網路介面執行個體。由於 PSC 網路連結已部署用戶端網路的多 NIC,因此 Vertex AI Pipelines 可以透過用戶端網路提供的路徑。
在本教學課程中,您將為 Vertex AI 管道建立完整的 Private Service Connect (PSC) 介面架構,利用 Cloud 防火牆規則允許或拒絕供應商與消費者的測試執行個體之間的連線,如圖 1 所示。
圖 1
您會在消費者虛擬私有雲網路中建立單一 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 Pipeline 子網路 (192.168.10.0/28) 存取 test-svc-2。根據 Log Explorer 產生的防火牆記錄,確認 PING 失敗。
課程內容
- 如何建立網路連結
- Vertex AI Pipelines 如何使用網路連結建立 PSC 介面
- 如何建立生產者與消費者之間的通訊
- 如何允許 Vertex AI Pipelines 存取消費者 VM test-svc-1
- 如何使用 Cloud 防火牆拒絕 Verex AI 管道存取消費者 VM test-svc-2
軟硬體需求
- Google Cloud 專案
- 身分與存取權管理權限
- Compute 執行個體管理員 (roles/compute.instanceAdmin)
- Compute 網路管理員 (roles/compute.networkAdmin)
- Compute 安全管理員 (roles/compute.securityAdmin)
- 受 IAP 保護的通道使用者 (roles/iap.tunnelResourceAccessor)
- Logging 管理員 (roles/logging.admin)
- Notebooks 管理員 (roles/notebooks.admin)
- 專案 IAM 管理員 (roles/resourcemanager.projectIamAdmin)
- 配額管理員 (roles/servicemanagement.quotaAdmin)
- 服務帳戶管理員 (roles/iam.serviceAccountAdmin)
- 服務帳戶使用者 (roles/iam.serviceAccountUser)
- Vertex AI 管理員 (roles/aiplatform.admin)
2. 事前準備
本教學課程會使用 $變數,協助您在 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. 消費者設定
建立消費者虛擬私有雲
在 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 設定
由於 Notebook 執行個體沒有外部 IP 位址,因此本教學課程會使用 Cloud 網路位址轉譯 (NAT) 來下載 Notebook 軟體套件。Cloud NAT 提供出站 NAT 功能,也就是說,網際網路主機不得與使用者管理的 Notebook 啟動通訊,因此 Notebook 的安全性更高。
在 Cloud Shell 中建立區域性雲端路由器。
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 連線至您的 VM 執行個體,請根據以下條件建立防火牆規則:
- 套用至所有您希望能透過 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. 建立消費者 VM 執行個體
在 Cloud Shell 中建立消費者 VM 執行個體 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 中建立消費者 VM 執行個體 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 中,對測試 VM 執行個體執行描述。
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
請記下 psc-network-attachment URI,供應商在建立 Private Service Connect 介面時會使用這個值。
在下方範例中,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 Notebook。這個筆記本將用於部署 Pipeline 工作,以便從 Vertex AI Pipeline 傳送 PING 至測試執行個體。Vertex AI 管道與包含執行個體的用戶端網路之間的資料路徑會使用 Private Service Connect 網路介面。
建立使用者管理的服務帳戶
在下一節中,您將建立服務帳戶,並與教學課程中使用的 Vertex AI Workbench 執行個體建立關聯。
在本教學課程中,服務帳戶會套用下列角色:
在 Cloud Shell 中建立服務帳戶。
gcloud iam service-accounts create notebook-sa \
--display-name="notebook-sa"
在 Cloud Shell 中,更新具有 Storage 管理員角色的服務帳戶。
gcloud projects add-iam-policy-binding $projectid --member="serviceAccount:notebook-sa@$projectid.iam.gserviceaccount.com" --role="roles/storage.admin"
在 Cloud Shell 中,更新具備 Vertex AI 使用者角色的服務帳戶。
gcloud projects add-iam-policy-binding $projectid --member="serviceAccount:notebook-sa@$projectid.iam.gserviceaccount.com" --role="roles/aiplatform.user"
在 Cloud Shell 中,更新具有 Artifact Registry 管理員角色的服務帳戶。
gcloud projects add-iam-policy-binding $projectid --member="serviceAccount:notebook-sa@$projectid.iam.gserviceaccount.com" --role="roles/artifactregistry.admin"
在 Cloud Shell 中,允許筆記本服務帳戶使用 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 執行個體
在下一節中,建立 Vertex AI Workbench 執行個體,並納入先前建立的服務帳戶 notebook-sa。
在 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 流量。這個 OS 工作階段將用於驗證 Vertex AI Pipeline 和 VM 之間的通訊。
sudo tcpdump -i any icmp -nn
9. Vertex AI 服務代理人更新
Vertex AI 管道會代您執行操作,例如從用來建立 PSC 介面的 PSC 網路連結子網路中取得 IP 位址。為此,Vertex AI Pipelines 會使用服務代理 (如下所列),該代理需要網路管理員權限。
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 執行個體名稱旁的「Open JupyterLab」(開啟 JupyterLab)。Vertex AI Workbench 執行個體會在 JupyterLab 中開啟。
- 依序選取「File」>「New」>「Notebook」
- 選取「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}")
如要確認執行作業是否成功,系統會列印服務帳戶和專案編號
- 在新的 Notebook 儲存格中,授予服務帳戶權限,以便在先前步驟中建立的值區中讀取及寫入管道成果物。
! 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
- 在新的 Notebook 儲存格中執行公用函式,等待管道完成
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')
- 在新的 Notebook 儲存格中,更新 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 管道已成功執行 PING 作業,並收到 test-svc-1 的回應。
如要驗證 Vertex AI 管道和 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 管道子網路 (192.168.10.0/28) 的流量,並將流量導向 test-svc-2。接著,您會更新 Notebook 以反映 test-svc-2 IP 位址,然後執行管道工作。
在 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
從筆記本儲存格執行管道工作
在新的 Notebook 儲存格中,更新 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}")
執行後,pipeline 工作約需 8 分鐘才能完成。
14. 驗證無法連線至 test-svc-2
在用於執行管道工作格的儲存格中,請注意狀態從 PIPELINE_STATE_PENDING 轉換為 PIPELINE_STATE_FAILED,表示 Vertex AI 管道和 test-svc-2 的回應無法成功執行 ping 作業。
您可以使用 Log Explorer 查看符合輸入拒絕規則的防火牆記錄項目,該規則包含 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 介面,並透過實作 Ingress 允許和拒絕防火牆,驗證了消費者和供應商的連線。
您已建立消費者基礎架構,並新增網路連結,讓 Vertex AI Pipelines 服務建立 PSC 介面 VM,以便連結消費者和供應商的通訊。您已瞭解如何在消費者 VPC 網路中建立防火牆規則,允許或拒絕與消費者網路中執行個體的連線。
Cosmopup 認為教學課程很棒!