連線至 VPC Service Controls 範圍內的內部 Cloud Run 服務

本教學課程說明如何將 Customer Experience Agent Studio (CX Agent Studio,Gemini Enterprise for Customer Experience 的一部分),私密連線至託管於 Cloud Run 的私人 Webhook 服務。這個架構會透過 Service Directory 私人網路存取權,將 Google 代管租戶專案的流量,透過 Shared VPC 網路轉送至區域性內部應用程式負載平衡器,同時保護 VPC Service Controls 服務範圍內的所有資源。

本教學課程適用於平台工程師、網路架構師和代理開發人員,協助他們避免代理與後端之間的流量進入公開網際網路。

參考架構:將流量從 CX Agent Studio 透過 Service Directory、內部負載平衡器和 Shared VPC 轉送至 Cloud Run。

目標

  • 設定 VPC Service Controls perimeter,保護 Shared VPC 主專案和服務專案中的 CX Agent Studio、Cloud Run 和 Service Directory。
  • 佈建服務代理,並在主專案和服務專案之間,授予跨專案 Identity and Access Management (IAM) 角色。
  • 部署 Cloud Run 服務,並設定內部輸入和直接虛擬私有雲 (VPC) 輸出。
  • 佈建區域性內部應用程式負載平衡器,並搭配無伺服器網路端點群組 (NEG) 和自行管理的傳輸層安全標準 (TLS) 憑證,然後在 Service Directory 註冊負載平衡器。
  • 在 CX Agent Studio 中設定 OpenAPI 工具,呼叫私人 Cloud Run 服務,並在模擬器中驗證連線。

費用

在本教學課程中,您會使用下列 Google Cloud計費元件:

您可以使用 Pricing Calculator 根據預測用量估算費用。

事前準備

本教學課程假設您的 Google Cloud 組織、資源階層和基礎共用虛擬私有雲網路已就緒:

  • 共用虛擬私有雲主專案:託管共用虛擬私有雲網路和 Service Directory 登錄檔的 Google Cloud 專案。
  • 服務專案: Google Cloud 附加至 Shared VPC 虛擬私有雲網路的專案,其中包含 CX Agent Studio 代理應用程式、Cloud Run 服務和區域性內部應用程式負載平衡器。
  • 共用虛擬私有雲網路:自訂模式共用虛擬私有雲網路 (例如 gecx-shared-vpc),在目標區域 (例如 us-east4) 中有三個專屬、不重疊的子網路:
    • 負載平衡器子網路 (例如 gecx-lb-subnet):為內部應用程式負載平衡器前端分配靜態內部虛擬 IP (VIP)。
    • 區域性代管 Proxy 專用子網路 (例如 gecx-proxy-subnet):以 Envoy 為基礎的區域性內部應用程式負載平衡器,需要使用有效的 Proxy 專用子網路 (--purpose=REGIONAL_MANAGED_PROXY --role=ACTIVE,建議使用 /23 以上)。
    • 直連虛擬私有雲輸出子網路 (例如 gecx-egress-subnet):Cloud Run 用於直連虛擬私有雲輸出的專用子網路 (建議使用 /26 以上)。
  • 指令列工具:Cloud Shell 或本機終端機,已安裝 Google Cloud CLI 和 openssl。

如需從頭建立 Shared VPC 虛擬私有雲網路及其三個子網路,請在設定環境變數後,執行「建立 Shared VPC 虛擬私有雲網路和子網路」中的選用指令。

必要的角色

如要取得完成本教學課程所需的權限,請要求管理員授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

準備環境

初始化殼層環境變數、啟用必要的 API,並視需要建立 Shared VPC 網路和子網路。

設定環境變數

在 Cloud Shell 或本機終端機中,設定下列環境變數:

# Organization and VPC Service Controls policy identifiers
export ORG_ID="ORGANIZATION_ID"
export PERIMETER_NAME="gecx_vpcsc_perimeter"
export PERIMETER_TITLE="GECX Agent Studio Perimeter"

# Shared VPC host and service project identifiers
export HOST_PROJECT_ID="HOST_PROJECT_ID"
export SERVICE_PROJECT_ID="SERVICE_PROJECT_ID"
export HOST_PROJECT_NUMBER=$(gcloud projects describe "${HOST_PROJECT_ID}" \
    --format="value(projectNumber)")
export SERVICE_PROJECT_NUMBER=$(gcloud projects describe \
    "${SERVICE_PROJECT_ID}" --format="value(projectNumber)")

# Networking and region configuration
export REGION="us-east4"
export VPC_NAME="gecx-shared-vpc"
export LB_SUBNET="gecx-lb-subnet"
export PROXY_SUBNET="gecx-proxy-subnet"
export EGRESS_SUBNET="gecx-egress-subnet"

# Cloud Run and internal load balancer resource names
export CLOUDRUN_SERVICE_NAME="hello-world"
export SERVERLESS_NEG_NAME="hello-world-neg"
export BACKEND_SERVICE_NAME="hello-world-backend-svc"
export URL_MAP_NAME="hello-world-url-map"
export CERTIFICATE_NAME="hello-world-ssl-cert"
export TARGET_PROXY_NAME="hello-world-https-proxy"
export ADDRESS_NAME="hello-world-lb-vip"
export FORWARDING_RULE_NAME="hello-world-fwd-rule"

# Internal FQDN for the TLS certificate and OpenAPI tool specification.
# This FQDN doesn't need to be registered in public DNS because Service
# Directory routes requests directly to the load balancer VIP while preserving
# this Host header and SNI.
export FQDN="hello.internal.example.com"

# Service Directory resource names
export NAMESPACE_NAME="gecx-namespace"
export SERVICE_NAME="hello-world-sd-service"
export ENDPOINT_NAME="hello-world-sd-endpoint"

更改下列內容:

  • ORGANIZATION_ID:您的 Google Cloud 組織 ID
  • HOST_PROJECT_ID:Shared VPC 主機專案的專案 ID
  • SERVICE_PROJECT_ID:服務專案的專案 ID

啟用必要的 API

在主專案和服務專案中啟用必要的 Google Cloud API,並設定配額專案,讓組織層級的 Access Context Manager 指令能順利執行:

# Enable APIs in the Shared VPC host project
gcloud services enable \
    compute.googleapis.com \
    run.googleapis.com \
    servicedirectory.googleapis.com \
    accesscontextmanager.googleapis.com \
    --project="${HOST_PROJECT_ID}"

# Enable APIs in the service project
gcloud services enable \
    compute.googleapis.com \
    run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com \
    servicedirectory.googleapis.com \
    ces.googleapis.com \
    contactcenterinsights.googleapis.com \
    dialogflow.googleapis.com \
    accesscontextmanager.googleapis.com \
    --project="${SERVICE_PROJECT_ID}"

# Set the quota project for organization-level Access Context Manager commands
gcloud config set billing/quota_project "${HOST_PROJECT_ID}"

建立 Shared VPC 網路和子網路 (選用)

如果您已有 Shared VPC 網路和子網路,請略過本節。

  1. 在主專案啟用 Shared VPC,並附加服務專案:

    gcloud compute shared-vpc enable "${HOST_PROJECT_ID}"
    
    gcloud compute shared-vpc associated-projects add "${SERVICE_PROJECT_ID}" \
        --host-project="${HOST_PROJECT_ID}"
    
  2. 在目標區域中建立自訂模式 Shared VPC 網路和三個必要子網路:

    gcloud compute networks create "${VPC_NAME}" \
        --subnet-mode=custom \
        --bgp-routing-mode=regional \
        --project="${HOST_PROJECT_ID}"
    
    gcloud compute networks subnets create "${LB_SUBNET}" \
        --network="${VPC_NAME}" \
        --region="${REGION}" \
        --range=10.200.1.0/24 \
        --project="${HOST_PROJECT_ID}"
    
    gcloud compute networks subnets create "${PROXY_SUBNET}" \
        --network="${VPC_NAME}" \
        --region="${REGION}" \
        --range=10.200.2.0/23 \
        --purpose=REGIONAL_MANAGED_PROXY \
        --role=ACTIVE \
        --project="${HOST_PROJECT_ID}"
    
    gcloud compute networks subnets create "${EGRESS_SUBNET}" \
        --network="${VPC_NAME}" \
        --region="${REGION}" \
        --range=10.200.4.0/24 \
        --project="${HOST_PROJECT_ID}"
    

設定 VPC Service Controls perimeter

確認 Shared VPC 主機專案和服務專案都屬於同一個 VPC Service Controls 範圍,且該範圍限制下列服務:

  • Customer Engagement Suite API (ces.googleapis.com)
  • Contact Center AI Insights API (contactcenterinsights.googleapis.com)
  • Dialogflow API (dialogflow.googleapis.com)
  • Cloud Run Admin API (run.googleapis.com)
  • Service Directory API (servicedirectory.googleapis.com)

一項專案一次只能屬於一個一般 VPC Service Controls service perimeter。

  1. 找出有效的組織層級存取權政策 ID (不含範圍政策):

    export POLICY_ID=$(gcloud access-context-manager policies list \
        --organization="${ORG_ID}" \
        --filter="NOT scopes:*" \
        --format="value(name.basename())" | head -n 1)
    
  2. 如果兩個專案都不屬於任何 service perimeter,請建立一個包含這兩個專案的 perimeter:

    gcloud access-context-manager perimeters create "${PERIMETER_NAME}" \
        --title="${PERIMETER_TITLE}" \
        --policy="${POLICY_ID}" \
        --resources="projects/${HOST_PROJECT_NUMBER},projects/${SERVICE_PROJECT_NUMBER}" \
        --restricted-services="ces.googleapis.com,contactcenterinsights.googleapis.com,dialogflow.googleapis.com,run.googleapis.com,servicedirectory.googleapis.com"
    

    如果任一專案已屬於某個 service perimeter,請改為更新現有的 perimeter:

    gcloud access-context-manager perimeters update "${PERIMETER_NAME}" \
        --policy="${POLICY_ID}" \
        --add-resources="projects/${HOST_PROJECT_NUMBER},projects/${SERVICE_PROJECT_NUMBER}" \
        --add-restricted-services="ces.googleapis.com,contactcenterinsights.googleapis.com,dialogflow.googleapis.com,run.googleapis.com,servicedirectory.googleapis.com"
    
  3. 選用:如果您是從 perimeter 外部的本機工作站執行 gcloud CLI 部署指令,而非從 Cloud Shell 執行,請為管理員身分設定暫時輸入規則,範圍限定為受信任的存取層級、教學課程專案和受限制的服務。

    如要更新現有 perimeter,請先匯出其輸入規則:

    gcloud access-context-manager perimeters describe "${PERIMETER_NAME}" \
        --policy="${POLICY_ID}" \
        --format="yaml(status.ingressPolicies)"
    

    如果輸出內容包含 status.ingressPolicies 下方的項目,請將這些清單項目儲存至備份檔案 (例如 existing_ingress.yaml),但不包含外部 status: 和 ingressPolicies: 鍵。

    使用臨時輸入規則建立 admin_ingress.yaml:

    cat << EOF > admin_ingress.yaml
    - ingressFrom:
        identities:
        - user:ADMIN_EMAIL
        sources:
        - accessLevel: "accessPolicies/${POLICY_ID}/accessLevels/ACCESS_LEVEL_NAME"
      ingressTo:
        operations:
        - serviceName: "ces.googleapis.com"
          methodSelectors:
          - method: "*"
        - serviceName: "contactcenterinsights.googleapis.com"
          methodSelectors:
          - method: "*"
        - serviceName: "dialogflow.googleapis.com"
          methodSelectors:
          - method: "*"
        - serviceName: "run.googleapis.com"
          methodSelectors:
          - method: "*"
        - serviceName: "servicedirectory.googleapis.com"
          methodSelectors:
          - method: "*"
        resources:
        - "projects/${HOST_PROJECT_NUMBER}"
        - "projects/${SERVICE_PROJECT_NUMBER}"
    EOF
    

    更改下列內容:

    • ADMIN_EMAIL:管理員帳戶的電子郵件地址,例如 dana@example.com。
    • ACCESS_LEVEL_NAME:組織存取層級的名稱,可依公司 IP 範圍或裝置政策限制存取權。如要在非正式環境中進行臨時測試,可以將整個 accessLevel 值替換為 "*"。

    如果您將現有的輸入規則匯出至 existing_ingress.yaml,請將這些規則附加至 admin_ingress.yaml,然後將輸入政策套用至 perimeter:

    gcloud access-context-manager perimeters update "${PERIMETER_NAME}" \
        --policy="${POLICY_ID}" \
        --set-ingress-policies=admin_ingress.yaml
    

    部署完成後,請移除這項臨時規則。

佈建服務代理並授予 IAM 角色

CX Agent Studio 和 Cloud Run 都會使用服務專案中 Google 代管的服務代理,這些代理需要 Shared VPC 主專案和服務專案的權限。

佈建服務代理

如果您最近在服務專案中啟用了 API,請先佈建 Customer Engagement Suite 服務代理和 Cloud Run 服務代理,確保其身分存在,再授予 IAM 角色:

# Provision the Customer Engagement Suite service agent:
# service-${SERVICE_PROJECT_NUMBER}@gcp-sa-ces.iam.gserviceaccount.com
gcloud beta services identity create \
    --service=ces.googleapis.com \
    --project="${SERVICE_PROJECT_ID}"

# Provision the Cloud Run service agent:
# service-${SERVICE_PROJECT_NUMBER}@serverless-robot-prod.iam.gserviceaccount.com
gcloud beta services identity create \
    --service=run.googleapis.com \
    --project="${SERVICE_PROJECT_ID}"

將角色授予 Customer Engagement Suite 服務代理

Customer Engagement Suite 服務代理 (service-${SERVICE_PROJECT_NUMBER}@gcp-sa-ces.iam.gserviceaccount.com) 須具備下列 IAM 角色:

目標資源 IAM 角色 目的
主專案 (HOST_PROJECT_ID) Service Directory 檢視者 (roles/servicedirectory.viewer) 允許 CX Agent Studio 解析主專案中的 Service Directory 服務和端點。
主專案 (HOST_PROJECT_ID) Private Service Connect 已授權服務 (roles/servicedirectory.pscAuthorizedService) 授權 CX Agent Studio 透過 Service Directory 私人網路存取權,將私人流量傳送至 Shared VPC 網路。
服務專案 (SERVICE_PROJECT_ID) Service Directory 檢視者 (roles/servicedirectory.viewer) 如果 Service Directory 服務位於其他專案,則必須在代理專案中啟用。
Cloud Run 服務 (CLOUDRUN_SERVICE_NAME) Cloud Run 叫用者 (roles/run.invoker) 授權 CX Agent Studio 服務代理 OIDC ID 權杖,叫用已驗證的 Cloud Run 服務。部署服務後授予。

部署 Cloud Run 服務後,您會直接在該服務上授予 roles/run.invoker。首先,將專案層級的 Service Directory 角色授予 Customer Engagement Suite 服務代理:

# Grant Service Directory roles on the host project
for ROLE in \
    roles/servicedirectory.viewer \
    roles/servicedirectory.pscAuthorizedService; do
  gcloud projects add-iam-policy-binding "${HOST_PROJECT_ID}" \
      --member="serviceAccount:service-${SERVICE_PROJECT_NUMBER}@gcp-sa-ces.iam.gserviceaccount.com" \
      --role="${ROLE}"
done

# Grant Service Directory Viewer on the service project
gcloud projects add-iam-policy-binding "${SERVICE_PROJECT_ID}" \
    --member="serviceAccount:service-${SERVICE_PROJECT_NUMBER}@gcp-sa-ces.iam.gserviceaccount.com" \
    --role="roles/servicedirectory.viewer"

授予 Cloud Run egress 和來源建構作業的角色

服務專案中的 Cloud Run 服務必須先具備查看 Shared VPC 網路和使用輸出子網路的權限,才能連結至主專案中的 Shared VPC 子網路,以便進行直連虛擬私有雲輸出。service-${SERVICE_PROJECT_NUMBER}@serverless-robot-prod.iam.gserviceaccount.com

請遵循最小權限原則,將主專案的 Compute 網路檢視者 (roles/compute.networkViewer) 角色,以及專用直連虛擬私有雲輸出子網路 (EGRESS_SUBNET) 的 Compute 網路使用者 (roles/compute.networkUser) 角色,授予 Cloud Run 服務代理。此外,請將服務專案的 Cloud Run 建構工具 (roles/run.builder) 授予 Compute Engine 預設服務帳戶 (${SERVICE_PROJECT_NUMBER}-compute@developer.gserviceaccount.com),這樣一來,即使停用預設編輯者授予,gcloud run deploy --source=. 也能從來源建構。

  1. 將必要角色授予 Cloud Run 服務代理和 Compute Engine 預設服務帳戶:

    # Grant Compute Network Viewer on the host project
    gcloud projects add-iam-policy-binding "${HOST_PROJECT_ID}" \
        --member="serviceAccount:service-${SERVICE_PROJECT_NUMBER}@serverless-robot-prod.iam.gserviceaccount.com" \
        --role="roles/compute.networkViewer"
    
    # Grant Compute Network User on the Direct VPC egress subnet
    gcloud compute networks subnets add-iam-policy-binding "${EGRESS_SUBNET}" \
        --region="${REGION}" \
        --member="serviceAccount:service-${SERVICE_PROJECT_NUMBER}@serverless-robot-prod.iam.gserviceaccount.com" \
        --role="roles/compute.networkUser" \
        --project="${HOST_PROJECT_ID}"
    
    # Grant Cloud Run Builder on the service project for source deployments
    gcloud projects add-iam-policy-binding "${SERVICE_PROJECT_ID}" \
        --member="serviceAccount:${SERVICE_PROJECT_NUMBER}-compute@developer.gserviceaccount.com" \
        --role="roles/run.builder"
    
  2. 確認 Cloud Run 服務代理在服務專案中,仍具備預設的 Cloud Run 服務代理 (roles/run.serviceAgent) 角色:

    gcloud projects get-iam-policy "${SERVICE_PROJECT_ID}" \
        --flatten="bindings" \
        --filter="bindings.role:roles/run.serviceAgent"
    

部署 Cloud Run 服務

部署前,請先詳閱直連虛擬私有雲輸出限制。

由於 CX Agent Studio OpenAPI 工具需要 JSON 酬載 ({"message": "..."}),因此請建立輕量級 Python Flask 應用程式,傳回 JSON 回應,並部署至 Cloud Run,同時附加內部輸入、IAM 驗證,以及連結至 Shared VPC 子網路的直連虛擬私有雲輸出。

  1. 建立 JSON Webhook 範例應用程式檔案:

    mkdir -p hello-world-service && cd hello-world-service
    
    cat << 'EOF' > main.py
    import os
    from datetime import datetime, timezone
    from flask import Flask, jsonify
    
    app = Flask(__name__)
    
    @app.route("/", methods=["GET"])
    def hello_world():
        return jsonify({
            "message": (
                "This is an affirmative response to your Hello World at "
                f"{datetime.now(timezone.utc).isoformat()}"
            )
        }), 200
    
    if __name__ == "__main__":
        app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
    EOF
    
    cat << 'EOF' > requirements.txt
    Flask==3.0.3
    gunicorn==22.0.0
    EOF
    
    cat << 'EOF' > Procfile
    web: gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app
    EOF
    
  2. 部署 Cloud Run 服務,並設定內部輸入和直連虛擬私有雲輸出:

    gcloud run deploy "${CLOUDRUN_SERVICE_NAME}" \
        --source=. \
        --ingress=internal \
        --no-allow-unauthenticated \
        --network="projects/${HOST_PROJECT_ID}/global/networks/${VPC_NAME}" \
        --subnet="projects/${HOST_PROJECT_ID}/regions/${REGION}/subnetworks/${EGRESS_SUBNET}" \
        --vpc-egress=all-traffic \
        --max-instances=10 \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}"
    
    cd ..
    

    這項部署作業會使用下列重要旗標:

    • --ingress=internal:將傳入要求限制為內部虛擬私有雲來源和內部應用程式負載平衡器。
    • --no-allow-unauthenticated:對所有傳入要求強制執行 Cloud Run IAM 驗證 (roles/run.invoker)。
    • --vpc-egress:控制 Cloud Run 容器的傳出轉送。使用 all-traffic 透過 Shared VPC 輸出子網路傳送所有傳出流量,或使用 private-ranges-only 僅透過子網路傳送目的地為 RFC 1918 和內部 IP 位址的流量。
    • --max-instances=10:限制並行 Cloud Run 執行個體的數量上限。使用直連虛擬私有雲輸出時,IP 位址消耗量會隨著使用中的執行個體數量而增加 (在修訂版本推出期間,最多可達 max-instances 的兩倍)。請確認 EGRESS_SUBNET 的 CIDR 範圍夠大 (建議為 /26 以上)。
    • --network-tags (選用):您可以在修訂版本層級新增網路標記 (例如 --network-tags=cloudrun-webhook),將精細的 VPC 防火牆規則套用至 Cloud Run 服務的傳出流量。
  3. 遵循最小權限原則,直接在 hello-world Cloud Run 服務上,將 Cloud Run 叫用者 (roles/run.invoker) 角色授予 Customer Engagement Suite 服務代理:

    gcloud run services add-iam-policy-binding "${CLOUDRUN_SERVICE_NAME}" \
        --region="${REGION}" \
        --member="serviceAccount:service-${SERVICE_PROJECT_NUMBER}@gcp-sa-ces.iam.gserviceaccount.com" \
        --role="roles/run.invoker" \
        --project="${SERVICE_PROJECT_ID}"
    

設定區域性內部應用程式負載平衡器

在 Shared VPC 環境中,您必須在與 Cloud Run 服務 (SERVICE_PROJECT_ID) 相同的專案中建立無伺服器 NEG。至於負載平衡器本身, Google Cloud 支援兩種部署模式:

  • 單一服務專案 (本教學課程使用):在 SERVICE_PROJECT_ID 中建立所有負載平衡器元件 (無伺服器 NEG、後端服務、網址對應、SSL 憑證、目標 HTTPS Proxy、保留的內部 IP 位址和轉送規則),並參照 HOST_PROJECT_ID 中的共用虛擬私有雲網路和 LB_SUBNET。
  • 跨專案參照服務 (多個服務專案):如要將 HOST_PROJECT_ID 中單一區域性內部應用程式負載平衡器的流量,轉送至多個服務專案中的 Cloud Run 服務,請在 SERVICE_PROJECT_ID 建立無伺服器 NEG 和區域性後端服務,將後端服務的 Compute 負載平衡器服務使用者 (roles/compute.loadBalancerServiceUser) 角色授予主專案管理員,然後在 HOST_PROJECT_ID 建立網址對應、SSL 憑證、目標 HTTPS Proxy、保留 IP 位址和轉送規則。如需完整操作說明,請參閱「設定具備跨專案後端服務的負載平衡器」。

建立無伺服器 NEG 和後端服務

  1. 在 SERVICE_PROJECT_ID 建立無伺服器 NEG,並指向 Cloud Run 服務:

    gcloud compute network-endpoint-groups create "${SERVERLESS_NEG_NAME}" \
        --region="${REGION}" \
        --network-endpoint-type=serverless \
        --cloud-run-service="${CLOUDRUN_SERVICE_NAME}" \
        --project="${SERVICE_PROJECT_ID}"
    
  2. 建立區域性內部代管後端服務。指定 --protocol=HTTPS (無伺服器 NEG 會忽略這個參數,但由於 --protocol 預設為 TCP,因此仍須指定):

    gcloud compute backend-services create "${BACKEND_SERVICE_NAME}" \
        --load-balancing-scheme=INTERNAL_MANAGED \
        --protocol=HTTPS \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}"
    
  3. 將無伺服器 NEG 新增至區域性後端服務並設為後端:

    gcloud compute backend-services add-backend "${BACKEND_SERVICE_NAME}" \
        --region="${REGION}" \
        --network-endpoint-group="${SERVERLESS_NEG_NAME}" \
        --network-endpoint-group-region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}"
    

建立網址對應、TLS 憑證和目標 HTTPS Proxy

  1. 建立區域性網址對應,將傳入要求轉送至後端服務:

    gcloud compute url-maps create "${URL_MAP_NAME}" \
        --default-service="${BACKEND_SERVICE_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}"
    
  2. 為 ${FQDN} (hello.internal.example.com) 產生私密金鑰和自行簽署的 TLS 憑證,並將憑證轉換為 DER 格式,以便上傳至 CX Agent Studio,做為自訂憑證授權單位 (CA)。在正式環境中,請使用內部 PKI 或憑證授權單位服務核發的憑證:

    # Generate an RSA-2048 private key
    openssl genrsa -out server.key 2048
    
    # Create a certificate signing request (CSR) using server.key
    openssl req -new -sha256 -key server.key \
        -subj "/CN=${FQDN}" \
        -out server.csr
    
    # Sign the certificate with a Subject Alternative Name (SAN) matching $FQDN
    openssl x509 -req -days 3650 -sha256 \
        -in server.csr \
        -signkey server.key \
        -out server.crt \
        -extfile <(printf "subjectAltName=DNS:%s\n" "${FQDN}")
    
    # Convert the PEM certificate to DER format for CX Agent Studio upload
    openssl x509 -in server.crt -out server.der -outform DER
    

    如要進一步瞭解自行管理的憑證,請參閱「使用自行管理的 SSL 憑證」。

  3. 在 SERVICE_PROJECT_ID 中建立區域性自行管理的 SSL 憑證資源:

    gcloud compute ssl-certificates create "${CERTIFICATE_NAME}" \
        --certificate=server.crt \
        --private-key=server.key \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}"
    
  4. 建立區域性目標 HTTPS Proxy,並附加 SSL 憑證和網址對應:

    gcloud compute target-https-proxies create "${TARGET_PROXY_NAME}" \
        --ssl-certificates="${CERTIFICATE_NAME}" \
        --url-map="${URL_MAP_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}"
    

預留內部 IP 位址並建立轉送規則

  1. 從 Shared VPC 負載平衡器子網路 (LB_SUBNET) 保留靜態內部 IPv4 位址,並將分配的 IP 位址儲存在 LB_IP:

    gcloud compute addresses create "${ADDRESS_NAME}" \
        --region="${REGION}" \
        --subnet="projects/${HOST_PROJECT_ID}/regions/${REGION}/subnetworks/${LB_SUBNET}" \
        --project="${SERVICE_PROJECT_ID}"
    
    export LB_IP=$(gcloud compute addresses describe "${ADDRESS_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --format="value(address)")
    
    echo "Allocated Internal Load Balancer VIP: ${LB_IP}"
    
  2. 在通訊埠 443 上建立區域性內部代管轉送規則,將流量從 ${LB_IP} 轉送至目標 HTTPS Proxy:

    gcloud compute forwarding-rules create "${FORWARDING_RULE_NAME}" \
        --load-balancing-scheme=INTERNAL_MANAGED \
        --network="projects/${HOST_PROJECT_ID}/global/networks/${VPC_NAME}" \
        --subnet="projects/${HOST_PROJECT_ID}/regions/${REGION}/subnetworks/${LB_SUBNET}" \
        --address="${LB_IP}" \
        --region="${REGION}" \
        --target-https-proxy="${TARGET_PROXY_NAME}" \
        --target-https-proxy-region="${REGION}" \
        --ports=443 \
        --allow-global-access \
        --project="${SERVICE_PROJECT_ID}"
    

詳情請參閱「設定採用 Cloud Run 的區域性內部應用程式負載平衡器」。

在 Service Directory 註冊端點,並設定自訂目標對象

CX Agent Studio 需要註冊的 Service Directory 服務和網路連結端點,才能探索私人流量並轉送至內部負載平衡器 VIP (${LB_IP})。

建立 Service Directory 命名空間、服務和端點

  1. 在主專案的相同區域 (${REGION}) 建立 Service Directory 命名空間和服務:

    gcloud service-directory namespaces create "${NAMESPACE_NAME}" \
        --location="${REGION}" \
        --project="${HOST_PROJECT_ID}"
    
    gcloud service-directory services create "${SERVICE_NAME}" \
        --namespace="${NAMESPACE_NAME}" \
        --location="${REGION}" \
        --project="${HOST_PROJECT_ID}"
    
  2. 建立 Service Directory 端點,指向通訊埠 443 上的內部負載平衡器 IP 位址 (${LB_IP}),並與共用虛擬私有雲網路建立關聯。Service Directory 必須使用 HOST_PROJECT_NUMBER 和 locations/global/networks,才能存取網路路徑:

    gcloud service-directory endpoints create "${ENDPOINT_NAME}" \
        --project="${HOST_PROJECT_ID}" \
        --location="${REGION}" \
        --namespace="${NAMESPACE_NAME}" \
        --service="${SERVICE_NAME}" \
        --address="${LB_IP}" \
        --port=443 \
        --network="projects/${HOST_PROJECT_NUMBER}/locations/global/networks/${VPC_NAME}"
    
  3. 在 CX Agent Studio 設定 OpenAPI 工具時,請列印要使用的完整 Service Directory 服務名稱:

    echo "projects/${HOST_PROJECT_ID}/locations/${REGION}/namespaces/${NAMESPACE_NAME}/services/${SERVICE_NAME}"
    

在 Cloud Run 服務上設定自訂目標對象

CX Agent Studio 使用服務代理 ID 權杖驗證機制呼叫已驗證的 OpenAPI 工具時,會產生 Google 簽署的 OIDC ID 權杖,其目標對象 (aud) 宣告衍生自 OpenAPI 規格中的要求網址 (GET / 的 https://${FQDN}/)。

根據預設,Cloud Run 只接受自動生成 *.run.app 網址做為有效目標對象。Cloud Run 自訂目標對象驗證會執行完全字串比對,不支援萬用字元 (/*),因此請在 Cloud Run 服務上,將 https://${FQDN} 和 https://${FQDN}/ 都設為自訂目標對象:

gcloud run services update "${CLOUDRUN_SERVICE_NAME}" \
    --region="${REGION}" \
    --project="${SERVICE_PROJECT_ID}" \
    --set-custom-audiences="https://${FQDN},https://${FQDN}/"

驗證 Cloud Run 服務設定

  1. 說明 Cloud Run 服務並檢查 custom-audiences 註解:

    gcloud run services describe "${CLOUDRUN_SERVICE_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}"
    
    gcloud run services describe "${CLOUDRUN_SERVICE_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --format="value(metadata.annotations['run.googleapis.com/custom-audiences'])"
    

    輸出結果會與下列內容相似:

    Service hello-world in region us-east4
    URL:     https://hello-world-SERVICE_PROJECT_NUMBER.us-east4.run.app
    Ingress: internal
    Traffic:
      100% LATEST (currently hello-world-00002-abc)
    Scaling: Auto (Min: 0, Max: 10)
      Revision hello-world-00002-abc
      Container hello-world-1
        Port:            8080
        Memory:          512Mi
        CPU:             1000m
      Service account:   SERVICE_PROJECT_NUMBER-compute@developer.gserviceaccount.com
      Concurrency:       80
      Max instances:     10
      Timeout:           300s
      VPC access:
        Egress:          all-traffic
        Network:         projects/HOST_PROJECT_ID/global/networks/gecx-shared-vpc
        Subnet:          projects/HOST_PROJECT_ID/regions/us-east4/subnetworks/gecx-egress-subnet
    

    custom-audiences 註解輸出內容大致如下:

    ["https://hello.internal.example.com", "https://hello.internal.example.com/"]
    

    這項輸出內容包含下列值:

    • SERVICE_PROJECT_NUMBER:服務專案的專案編號
    • HOST_PROJECT_ID:Shared VPC 主機專案的專案 ID
  2. 確認輸出內容顯示 Ingress: internal、兩個自訂目標對象,以及附加至 ${VPC_NAME} 和 ${EGRESS_SUBNET} 的直連虛擬私有雲輸出。

設定 CX Agent Studio

建立代理應用程式,使用 Service Directory 和自訂 TLS 設定來設定 OpenAPI 工具,並將工具附加至根代理。

建立代理應用程式

  1. 開啟 CX Agent Studio 控制台。
  2. 選取服務專案 (SERVICE_PROJECT_ID) 和多區域位置 (us 或 eu)。CX Agent Studio 應用程式託管於多區域位置,而非單一 Google Cloud 區域 (例如 us-east4)。
  3. 按一下「Create agent」(建立代理),輸入 Hello_World 做為代理應用程式名稱,然後按一下「Create」(建立)。

建立 OpenAPI 工具

  1. 在代理建構工具導覽列中,點選「工具」。
  2. 點選「+ 建立」,將工具新增至代理應用程式。
  3. 選取「OpenAPI」OpenAPI做為工具類型。
  4. 在工具名稱中輸入 hello_world_GET。
  5. 在「OpenAPI schema (YAML)」編輯器中,輸入下列規格:

    openapi: 3.0.0
    info:
      title: Hello World Cloud Run Service
      description: Hello World service deployed on Cloud Run.
      version: 1.0.0
    servers:
      - url: https://FQDN
    paths:
      /:
        get:
          summary: Get Hello World message
          description: Returns an affirmative response with a timestamp.
          operationId: getHelloWorld
          responses:
            '200':
              description: Successful response
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      message:
                        type: string
                        example: >-
                          This is an affirmative response to your Hello World
    

    將 FQDN 替換為您為 TLS 憑證設定的網域名稱,例如 hello.internal.example.com。

  6. 在「Authentication」(驗證) 之下,選取「Service agent ID token」(服務代理 ID 權杖),讓 CX Agent Studio 在 Authorization: Bearer 標頭中附加 service-${SERVICE_PROJECT_NUMBER}@gcp-sa-ces.iam.gserviceaccount.com 的 Google 簽署 OIDC ID 權杖。

  7. 開啟「Advanced」(進階) 分頁,設定下列欄位:

    1. 自訂 TLS 憑證授權單位:上傳您先前產生的 server.der 檔案。
    2. Service Directory:輸入完整的 Service Directory 服務名稱:

      projects/HOST_PROJECT_ID/locations/REGION/namespaces/NAMESPACE_NAME/services/SERVICE_NAME
      

      更改下列內容:

      • HOST_PROJECT_ID:Shared VPC 主機專案的專案 ID
      • REGION:您建立 Service Directory 命名空間的區域,例如 us-east4
      • NAMESPACE_NAME:Service Directory 命名空間的名稱,例如 gecx-namespace
      • SERVICE_NAME:Service Directory 服務的名稱,例如 hello-world-sd-service
  8. 點選「建立」。

附加工具並設定指令

  1. 在代理建構工具畫布上,找到「Root agent」(根代理) 資訊卡,點選「Add tool」(新增工具),然後選取「hello_world_GET」。
  2. 在「Root agent」(根層級代理) 資訊卡中,開啟「Instructions」(指令) 面板,設定代理指令。

    在 CX Agent Studio 指令中參照 OpenAPI 工具作業時,請使用 {@TOOL: TOOLNAMEOPERATION_ID} 語法 (或在編輯器中輸入 @,然後從自動完成選單中選取工具,使其顯示為方塊)。對於工具 hello_world_GET (TOOL_NAME) 和 OpenAPI operationId getHelloWorld (OPERATION_ID),解析後的工具參照為 {@TOOL: hello_world_GET_getHelloWorld}。

  3. 輸入下列 XML 指令:

    <role>A direct and precise agent focused on completing a specific task.</role>
    <persona>
        <primary_goal>Prompt the user to type "Hello World", trigger the appropriate tool, and return the exact output from the tool with no additional commentary.</primary_goal>
    </persona>
    <constraints>
        <constraint>When returning the tool's output, you must output ONLY the exact message string returned by the tool. Do not include conversational filler, formatting, or additional text before or after the tool's output.</constraint>
    </constraints>
    <taskflow>
        These define the conversational subtasks that you can take. Each subtask has a sequence of steps that should be taken in order.
        <subtask name="Initial Engagement">
            <step name="Greet and Prompt">
                <trigger>User initiates conversation</trigger>
                <action>Greet the user and ask them to type exactly: "Hello World".</action>
            </step>
        </subtask>
        <subtask name="Process Hello World">
            <step name="Run Tool">
                <trigger>User responds with "Hello World"</trigger>
                <action>
                    Immediately call {@TOOL: hello_world_GET_getHelloWorld}.
                    Once the tool returns a response, provide the `message` from the JSON payload to the user.
                </action>
            </step>
        </subtask>
    </taskflow>
    <examples>
    </examples>
    
  4. 確認 {@TOOL: hello_world_GET_getHelloWorld} 醒目顯示為有效方塊,且沒有紅色底線,然後按一下「Save」(儲存)。

測試代理

使用模擬器驗證端對端私人連線:

  1. 在 CX Agent Studio 控制台中,按一下「Preview agent」(預覽代理),開啟模擬器面板。
  2. 輸入 hello,然後按下 Enter 鍵。代理會向您打招呼,並提示您輸入 "Hello World"。
  3. 輸入 Hello World,然後按下 Enter 鍵。代理會透過 Service Directory 私人網路存取權呼叫 hello_world_GET_getHelloWorld,並透過區域性內部應用程式負載平衡器,將流量轉送至您的私人 Cloud Run 服務,然後傳回確切的 JSON message 時間戳記酬載。

架構考量

將這個架構用於實際工作環境的工作負載時,請注意下列設計行為:

  • Cloud Run 自訂目標對象和 OpenAPI 路徑:Cloud Run 自訂目標對象驗證要求字串與 OIDC ID 權杖 aud 宣告完全相符,不支援萬用字元,例如 https://${FQDN}/*。根據預設,CX Agent Studio 在產生 ID 權杖目標對象時,會從要求網址中移除查詢參數,但會保留網址路徑。將 OpenAPI 規格中定義的所有靜態路徑 (例如 https://${FQDN}/ 或 https://${FQDN}/v1/orders) 新增至 Cloud Run 服務上的 --set-custom-audiences。使用自訂網域搭配 Cloud Run OIDC ID 權杖驗證時,請避免使用動態路徑參數 (例如 /items/{item_id});請將動態值做為查詢參數 (/items?item_id=100) 或在 POST 要求主體中傳遞,確保目標對象 URI 保持靜態。
  • 在單一負載平衡器後方,擴充至多個 Cloud Run 服務:您可以將多個區域性後端服務 (每個服務都由自己的無伺服器 NEG 支援) 附加至負載平衡器網址對應,並使用主機規則、路徑比對器或無伺服器 NEG 網址遮罩轉送要求,藉此將多個工具或代理連結至同一個區域性內部應用程式負載平衡器和 Service Directory 端點。
  • 多區域部署:Service Directory 是區域性服務,Service Directory 私人網路存取權支援相同區域中的區域性內部應用程式負載平衡器。如要提升多區域復原能力,請在每個目標區域部署區域性 Cloud Run 後端和區域性內部負載平衡器,並搭配相應的區域性 Service Directory 端點。
  • Service Directory 傳播延遲:Service Directory 端點解析和 IAM 角色授予作業最多會快取 90 秒。如果您更新端點 IP 位址或 IAM 政策,請等待 1 到 2 分鐘,再重新在模擬器中測試。

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程所用資源的費用,請刪除含有相關資源的專案,或者保留專案,但按照依附元件的反向順序刪除個別資源。

  1. 在 CX Agent Studio 控制台刪除 Hello_World 代理應用程式。

  2. 刪除 Service Directory 命名空間 (系統會自動刪除其服務和端點):

    gcloud service-directory namespaces delete "${NAMESPACE_NAME}" \
        --location="${REGION}" \
        --project="${HOST_PROJECT_ID}" \
        --quiet
    
  3. 刪除區域性內部應用程式負載平衡器元件和無伺服器 NEG:

    gcloud compute forwarding-rules delete "${FORWARDING_RULE_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --quiet
    
    gcloud compute addresses delete "${ADDRESS_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --quiet
    
    gcloud compute target-https-proxies delete "${TARGET_PROXY_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --quiet
    
    gcloud compute ssl-certificates delete "${CERTIFICATE_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --quiet
    
    gcloud compute url-maps delete "${URL_MAP_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --quiet
    
    gcloud compute backend-services delete "${BACKEND_SERVICE_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --quiet
    
    gcloud compute network-endpoint-groups delete "${SERVERLESS_NEG_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --quiet
    
  4. 刪除 Cloud Run 服務:

    gcloud run services delete "${CLOUDRUN_SERVICE_NAME}" \
        --region="${REGION}" \
        --project="${SERVICE_PROJECT_ID}" \
        --quiet
    
  5. 選用:如果您在打算保留的現有 VPC Service Controls perimeter,新增了臨時管理員輸入規則,請移除該規則。

    如果 perimeter 已有其他輸入規則,請還原備份輸入政策檔案:

    gcloud access-context-manager perimeters update "${PERIMETER_NAME}" \
        --policy="${POLICY_ID}" \
        --set-ingress-policies=EXISTING_INGRESS_FILE
    

    將 EXISTING_INGRESS_FILE 替換為包含 perimeter 先前輸入規則的 YAML 檔案路徑,例如 existing_ingress.yaml。

    如果 perimeter 沒有其他輸入規則,請清除輸入政策:

    gcloud access-context-manager perimeters update "${PERIMETER_NAME}" \
        --policy="${POLICY_ID}" \
        --clear-ingress-policies
    
  6. 選用:如果您建立 VPC Service Controls perimeter 和 Shared VPC 子網路,只是為了完成本教學課程,請刪除這些資源:

    gcloud access-context-manager perimeters delete "${PERIMETER_NAME}" \
        --policy="${POLICY_ID}" \
        --quiet
    
    gcloud compute networks subnets delete "${EGRESS_SUBNET}" \
        --region="${REGION}" \
        --project="${HOST_PROJECT_ID}" \
        --quiet
    
    gcloud compute networks subnets delete "${PROXY_SUBNET}" \
        --region="${REGION}" \
        --project="${HOST_PROJECT_ID}" \
        --quiet
    
    gcloud compute networks subnets delete "${LB_SUBNET}" \
        --region="${REGION}" \
        --project="${HOST_PROJECT_ID}" \
        --quiet
    
  7. 從工作站或 Cloud Shell 殼層環境中,移除本機應用程式、輸入政策和 TLS 憑證檔案:

    rm -rf hello-world-service server.key server.csr server.crt server.der \
        admin_ingress.yaml
    

後續步驟