This tutorial shows you how to connect Customer Experience Agent Studio (CX Agent Studio), part of Gemini Enterprise for Customer Experience, to private API servers hosted in an on-premises data center without traversing the public internet.
By default, CX Agent Studio runs in a Google-managed tenant project and routes outbound tool requests over the public internet. To reach private APIs hosted on-premises, you bridge the Google-managed tenant project to your Virtual Private Cloud (VPC) network using Service Directory private network access, and then route traffic through a regional internal Application Load Balancer over Cloud VPN or Cloud Interconnect. This tutorial is intended for platform engineers, network architects, and agent developers who manage hybrid Google Cloud connectivity.
Objectives
- Grant Identity and Access Management (IAM) roles to the Customer Engagement Suite service agent for Service Directory private network access.
- Configure a custom-mode VPC network with a load balancer subnet and a regional managed proxy-only subnet.
- Configure custom route advertisements on Cloud Router and set up Google Cloud and on-premises firewall rules.
- Deploy a hybrid connectivity network endpoint group (NEG) or a regional internet NEG behind a regional internal Application Load Balancer, and register the load balancer in Service Directory.
- Configure an OpenAPI tool in CX Agent Studio to call the on-premises API server and verify the connection in the simulator.
Costs
In this tutorial, you use the following billable components of Google Cloud:
- CX Agent Studio
- Cloud Load Balancing
- Service Directory
- Cloud VPN or Cloud Interconnect
- Cloud DNS (required only if you use a regional internet NEG)
- VPC
To generate a cost estimate based on your projected usage, use the pricing calculator.
Architecture
The following diagram shows the end-to-end private outbound networking flow from CX Agent Studio to an on-premises API server:

The request flow operates across the following components:
- CX Agent Studio and OpenAPI tool: When an agent invokes an OpenAPI tool configured with Service Directory, CX Agent Studio intercepts the outbound call instead of routing it to the public internet.
- Service Directory private network access: Service Directory resolves the target service to the internal virtual IP (VIP) address of your regional internal Application Load Balancer inside your VPC network and sends traffic over a private point-to-point connection.
- Regional internal Application Load Balancer: Although you can configure Service Directory per OpenAPI tool or toolset in CX Agent Studio to point directly to an on-premises endpoint, placing a regional internal Application Load Balancer behind Service Directory is recommended as a best practice. It provides a unified entry point that centralizes TLS termination, distributed Envoy health checks, and URL map host and path routing across multiple backend services.
- Hybrid connectivity NEG or regional internet NEG: The load balancer's Envoy proxies (running in the regional proxy-only subnet) forward requests to your on-premises endpoints defined in either a hybrid connectivity NEG or a regional internet NEG.
- Cloud Router and hybrid connectivity: Cloud Router advertises the regional proxy-only subnet to your on-premises router over Border Gateway Protocol (BGP) and routes traffic across Cloud VPN or Cloud Interconnect to your on-premises API server.
Choose a network endpoint group type
When configuring the regional internal Application Load Balancer to forward traffic to on-premises API servers, you can define your backend endpoints using either a hybrid connectivity NEG or a regional internet NEG.
Although regional internet NEGs are commonly used to reach external backends over the internet, managed Envoy proxies in a regional internal Application Load Balancer can also route regional internet NEG traffic over private VPC routes learned from Cloud Router (Cloud VPN or Cloud Interconnect) when the configured fully qualified domain name (FQDN) resolves to a private on-premises IP address through Cloud DNS.
The following table compares hybrid connectivity NEGs and regional internet NEGs for on-premises connectivity:
| Feature | Hybrid connectivity NEG | Regional internet NEG |
|---|---|---|
| API endpoint type | NON_GCP_PRIVATE_IP_PORT |
INTERNET_FQDN_PORT or INTERNET_IP_PORT |
| Resource scope | Zonal (--zone). Must be created in a specific zone within the region. |
Regional (--region). Operates across the entire region without a single-zone dependency. |
| Target addressing | Static private IPv4 address and port (IP:Port), such as 10.10.100.2:443. |
FQDN and port (FQDN:Port), such as api.onprem.example.com:443, or public IP:Port. |
| DNS requirement | None. Traffic routes directly to the configured IP address using BGP routes. | Requires Cloud DNS (private zone or DNS forwarding zone to on-premises DNS) to resolve private FQDNs to RFC 1918 IP addresses. |
| TLS SNI to backend | Doesn't populate the TLS HostName Server Name Indication (SNI) field when connecting to IP literals. |
Automatically sends the configured FQDN in the TLS ClientHello SNI extension during the backend TLS handshake. |
| Health checks | Distributed Envoy health checks originating from the regional proxy-only subnet. | Distributed Envoy health checks originating from the regional proxy-only subnet. |
| Backend balancing mode | Uses RATE balancing mode (--balancing-mode=RATE and --max-rate-per-endpoint). |
Pools resolved endpoints and distributes traffic using Envoy locality policies, such as ROUND_ROBIN. |
When to use a hybrid connectivity NEG
Choose a hybrid connectivity NEG (NON_GCP_PRIVATE_IP_PORT) in the following
scenarios:
- Static private IP addressing: Your on-premises API servers or internal
load balancers have fixed RFC 1918 IP addresses, and you want to route
directly to
IP:Portcombinations without maintaining Cloud DNS private zones or DNS forwarding rules. - Rate-based load balancing across multiple IPs: You want to configure
explicit request-rate targets (
--max-rate-per-endpoint) across multiple on-premises server IP addresses, or mix Google Cloud zonal NEGs (GCE_VM_IP_PORT) and on-premises endpoints in the same backend service during cloud migrations. - No backend SNI requirement: Your on-premises backend server doesn't require a hostname in the TLS SNI extension during the backend handshake.
When to use a regional internet NEG
Choose a regional internet NEG (INTERNET_FQDN_PORT) in the following
scenarios:
- Regional high availability without zonal dependency: Because hybrid
connectivity NEGs are zonal resources, Google Cloud recommends using a
regional internet NEG with
INTERNET_FQDN_PORTand a private Cloud DNS zone when you want to avoid a single zonal configuration dependency. - Dynamic DNS resolution: Your on-premises API sits behind an on-premises load balancer, Kubernetes ingress controller, or API gateway whose IP addresses change dynamically in DNS. Envoy periodically re-resolves the FQDN based on the DNS time to live (TTL).
- Backend TLS SNI requirement: Your on-premises HTTPS server or API gateway hosts multiple virtual domains on the same IP address and requires the load balancer to send the target hostname in the TLS SNI extension during the backend handshake.
- Private access to Google APIs (
*.googleapis.com) under VPC Service Controls: When VPC Service Controls blocks direct public egress from CX Agent Studio, a regional internet NEG (INTERNET_FQDN_PORT) can also route tool calls to Google APIs through your VPC network. The Envoy proxies resolve the FQDN by using your VPC network's Cloud DNS configuration and send it in the TLS SNI extension andHostheader. Because proxy-only subnets don't support Private Google Access, choose one of the following egress paths:- Private Service Connect endpoint for Google APIs: Create a
Private Service Connect endpoint with the
vpc-scAPI bundle (an internal VPC IP address that is equivalent torestricted.googleapis.com) and a private Cloud DNS zone that resolves*.googleapis.comto that address. Traffic to the endpoint stays inside your VPC network, so you don't need a route to the default internet gateway. - Private Google Access VIPs with Cloud NAT: Resolve
*.googleapis.comtorestricted.googleapis.com(199.36.153.4/30) orprivate.googleapis.com(199.36.153.8/30), add a route for that range to the default internet gateway, and configure a Cloud NAT gateway for the proxy-only subnet (endpoint typeENDPOINT_TYPE_MANAGED_PROXY_LB). - For both paths: Don't attach a health check to the backend service
because an unauthenticated probe to
GET /on*.googleapis.comreturns a4xxresponse and marks the endpoint unhealthy. Keep the VPC network project, the CX Agent Studio project, and the target Google API resources in the same service perimeter, and configure authentication on the OpenAPI tool.
- Private Service Connect endpoint for Google APIs: Create a
Private Service Connect endpoint with the
Before you begin
Verify that you have the following prerequisites in place:
- Hybrid connectivity to on-premises: An active HA VPN
tunnel or Cloud Interconnect VLAN attachment connecting your
Google Cloud project to your on-premises network in your target region
(for example,
us-central1), managed by a Cloud Router. - On-premises API server: An HTTP or HTTPS API server running on-premises
(for example,
10.10.100.2listening on port443) that is reachable from your on-premises router. If you don't have an API server ready for testing, see Deploy a sample on-premises API server (optional). - Command-line tools: Cloud Shell or a local terminal with the
Google Cloud CLI and
opensslinstalled.
Required roles
To get the permissions that you need to complete this tutorial, ask your administrator to grant you the following IAM roles on your project:
- Compute Network Admin (
roles/compute.networkAdmin) - Compute Load Balancer Admin (
roles/compute.loadBalancerAdmin) - Compute Security Admin (
roles/compute.securityAdmin) - Service Directory Editor (
roles/servicedirectory.editor) - Service Directory Network Attacher (
roles/servicedirectory.networkAttacher) - Project IAM Admin (
roles/resourcemanager.projectIamAdmin) - Service Usage Admin (
roles/serviceusage.serviceUsageAdmin) - Gemini Enterprise for Customer Experience Admin (
roles/ces.admin) -
Configure Cloud DNS for a regional internet NEG:
DNS Administrator (
roles/dns.admin)
For more information about granting roles, see Manage access to projects, folders, and organizations.
You might also be able to get the required permissions through custom roles or other predefined roles.
Prepare the environment
In the Google Cloud console, activate Cloud Shell or open a local terminal with the gcloud CLI installed.
Set the environment variables for your deployment:
export PROJECT_ID="PROJECT_ID" export REGION="us-central1" export ZONE="us-central1-a" # Networking and Cloud Router variables export NETWORK_NAME="gecx-hybrid-vpc" export LB_SUBNET_NAME="gecx-lb-subnet" export LB_SUBNET_RANGE="10.0.1.0/24" export PROXY_ONLY_SUBNET_NAME="gecx-proxy-only-subnet" export PROXY_ONLY_SUBNET_RANGE="10.0.2.0/24" export ROUTER_NAME="CLOUD_ROUTER_NAME" # On-premises target variables export ON_PREM_CIDR="10.10.100.0/24" export ON_PREM_API_IP="10.10.100.2" export ON_PREM_API_PORT="443" export FQDN="api.onprem.example.com" # Load balancer and Service Directory variables export HYBRID_NEG_NAME="onprem-hybrid-neg" export INTERNET_NEG_NAME="onprem-regional-internet-neg" export HEALTH_CHECK_NAME="onprem-api-hc" export BACKEND_SERVICE_NAME="onprem-api-backend" export URL_MAP_NAME="onprem-api-url-map" export CERTIFICATE_NAME="onprem-api-cert" export TARGET_PROXY_NAME="onprem-api-https-proxy" export ADDRESS_NAME="onprem-alb-vip" export FORWARDING_RULE_NAME="onprem-alb-forwarding-rule" export NAMESPACE_NAME="gecx-onprem-ns" export SERVICE_NAME="onprem-api-service" export ENDPOINT_NAME="onprem-alb-endpoint"Replace the following:
PROJECT_ID: your Google Cloud project IDCLOUD_ROUTER_NAME: the name of the Cloud Router inREGIONthat manages your Cloud VPN tunnel or Cloud Interconnect attachment
Configure the gcloud CLI to use your project and retrieve your project number:
gcloud config set project "${PROJECT_ID}" export PROJECT_NUMBER=$(gcloud projects describe "${PROJECT_ID}" \ --format="value(projectNumber)")Enable the required Google Cloud APIs:
gcloud services enable \ compute.googleapis.com \ servicedirectory.googleapis.com \ ces.googleapis.com \ dialogflow.googleapis.com \ dns.googleapis.com \ --project="${PROJECT_ID}"
Deploy a sample on-premises API server (optional)
If you already have an on-premises API server to test with, skip to Grant IAM roles to the Customer Engagement Suite service agent.
This section deploys a sample Python FastAPI Order Status API server on your
on-premises Linux host (for example, 10.10.100.2:443). The server listens over
HTTPS on port 443 and exposes two endpoints:
GET /: Responds with HTTP200 OK({"status": "healthy"}) to satisfy the regional internal Application Load Balancer's Envoy health check probes.GET /order/{order_number}: Returns an order fulfillment status (pending,processing,shipped,delivered, orcancelled) matching theOrderStatusOpenAPI 3.0 schema configured later in CX Agent Studio.
Generate a TLS certificate for port 443
On your on-premises Linux host (10.10.100.2), create a directory for the
service and generate a self-signed TLS certificate:
mkdir -p ~/order-status-api && cd ~/order-status-api
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout onprem.key \
-out onprem.crt \
-subj "/CN=api.onprem.example.com" \
-addext "subjectAltName=DNS:api.onprem.example.com,IP:10.10.100.2"
Create the FastAPI application
Create a main.py file inside ~/order-status-api:
from typing import Literal
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(
title="On-Premises Order Status API",
description="Retrieves order fulfillment status from the on-premises API server.",
version="1.0.0",
)
class OrderStatus(BaseModel):
order_number: str
status: Literal["pending", "processing", "shipped", "delivered", "cancelled"]
# Sample in-memory order database
SAMPLE_ORDERS: dict[
str, Literal["pending", "processing", "shipped", "delivered", "cancelled"]
] = {
"10042": "shipped",
"10043": "processing",
"10044": "delivered",
"10045": "pending",
"10046": "cancelled",
}
@app.get("/")
def health_check() -> dict[str, str]:
"""Health check endpoint for Google Cloud Envoy load balancer probes."""
return {"status": "healthy"}
@app.get(
"/order/{order_number}",
response_model=OrderStatus,
operation_id="getOrderStatus",
)
def get_order_status(order_number: str) -> OrderStatus:
"""Returns the current fulfillment status for a specific order number."""
order_state = SAMPLE_ORDERS.get(order_number, "processing")
return OrderStatus(order_number=order_number, status=order_state)
Start the HTTPS server
Start the server using either Python and Uvicorn or Docker:
Option A: Run with Python and Uvicorn
Create a Python virtual environment and install
fastapianduvicorn:python3 -m venv venv ./venv/bin/pip install --upgrade pip fastapi uvicornStart
uvicornlistening on0.0.0.0:443with TLS enabled:sudo ./venv/bin/uvicorn main:app \ --host 0.0.0.0 \ --port 443 \ --ssl-keyfile onprem.key \ --ssl-certfile onprem.crtOptional: To run the service persistently in the background using
systemd, create/etc/systemd/system/order-status-api.serviceand start the service:sudo tee /etc/systemd/system/order-status-api.service > /dev/null <<EOF [Unit] Description=On-Premises Order Status FastAPI Server After=network.target [Service] WorkingDirectory=${HOME}/order-status-api ExecStart=${HOME}/order-status-api/venv/bin/uvicorn main:app --host 0.0.0.0 --port 443 --ssl-keyfile onprem.key --ssl-certfile onprem.crt Restart=always RestartSec=3 [Install] WantedBy=multi-user.target EOF sudo systemctl daemon-reload sudo systemctl enable --now order-status-api
Option B: Run as a Docker container
Create a
Dockerfileinside~/order-status-api:cat << 'EOF' > Dockerfile FROM python:3.11-slim WORKDIR /app RUN pip install --no-cache-dir fastapi uvicorn COPY main.py onprem.key onprem.crt ./ EXPOSE 443 CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "443", "--ssl-keyfile", "onprem.key", "--ssl-certfile", "onprem.crt"] EOFBuild and start the container on port
443:docker build -t order-status-api . docker run -d --name order-status-api --restart unless-stopped -p 443:443 order-status-api
Verify the server locally
From your on-premises host, verify that the health check endpoint (/), the
order lookup endpoint (/order/10042), and the OpenAPI schema endpoint
(/openapi.json) respond over HTTPS:
Test the Envoy health check endpoint:
curl --cacert ~/order-status-api/onprem.crt https://10.10.100.2/The output is
{"status":"healthy"}.Test the OpenAPI tool endpoint:
curl --cacert ~/order-status-api/onprem.crt https://10.10.100.2/order/10042The output is
{"order_number":"10042","status":"shipped"}.Verify the auto-generated OpenAPI 3.0 schema:
curl --cacert ~/order-status-api/onprem.crt https://10.10.100.2/openapi.json
Grant IAM roles to the Customer Engagement Suite service agent
CX Agent Studio uses the Customer Engagement Suite service agent to resolve Service Directory services and send traffic into your VPC network over private network access.
Make sure that the Customer Engagement Suite service agent exists in your project:
gcloud beta services identity create \ --service=ces.googleapis.com \ --project="${PROJECT_ID}"The command returns a service account in the format
service-PROJECT_NUMBER@gcp-sa-ces.iam.gserviceaccount.com.Grant the Service Directory Viewer (
roles/servicedirectory.viewer) and Private Service Connect Authorized Service (roles/servicedirectory.pscAuthorizedService) roles to the service agent:for ROLE in \ roles/servicedirectory.viewer \ roles/servicedirectory.pscAuthorizedService; do gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ --member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-ces.iam.gserviceaccount.com" \ --role="${ROLE}" done
Configure the VPC network and subnets
A regional internal Application Load Balancer requires two subnets in the same region as your Cloud VPN tunnel or Cloud Interconnect attachment:
- A standard load balancer subnet to host the load balancer's internal forwarding rule VIP address.
- A regional managed proxy-only subnet (
REGIONAL_MANAGED_PROXY) where Google Cloud allocates IP addresses for the Envoy proxies that terminate client connections and initiate backend connections to your on-premises server.
If you are creating a new custom-mode VPC network, run the following command:
gcloud compute networks create "${NETWORK_NAME}" \ --subnet-mode=custom \ --bgp-routing-mode=global \ --project="${PROJECT_ID}"If you are using an existing VPC network that already has Cloud VPN or Cloud Interconnect attached, update its dynamic routing mode to
GLOBALinstead:gcloud compute networks update "${NETWORK_NAME}" \ --bgp-routing-mode=global \ --project="${PROJECT_ID}"Create the load balancer subnet in your target region:
gcloud compute networks subnets create "${LB_SUBNET_NAME}" \ --network="${NETWORK_NAME}" \ --region="${REGION}" \ --range="${LB_SUBNET_RANGE}" \ --project="${PROJECT_ID}"Create the regional managed proxy-only subnet in the same region:
gcloud compute networks subnets create "${PROXY_ONLY_SUBNET_NAME}" \ --purpose=REGIONAL_MANAGED_PROXY \ --role=ACTIVE \ --network="${NETWORK_NAME}" \ --region="${REGION}" \ --range="${PROXY_ONLY_SUBNET_RANGE}" \ --project="${PROJECT_ID}"
Configure custom route advertisements on Cloud Router
When the regional internal Application Load Balancer forwards tool requests or sends distributed
Envoy health check probes to your on-premises API server, the packets originate
from IP addresses in the regional proxy-only subnet (PROXY_ONLY_SUBNET_RANGE).
By default, Cloud Router advertises only standard VPC
subnets (ALL_SUBNETS) and doesn't advertise REGIONAL_MANAGED_PROXY subnets.
You must configure
custom route advertisements
on your Cloud Router so that your on-premises router learns the route
back to the proxy-only subnet.
Update your Cloud Router to advertise all visible VPC subnets along with the custom IP range of your regional proxy-only subnet:
gcloud compute routers update "${ROUTER_NAME}" \ --region="${REGION}" \ --advertisement-mode=CUSTOM \ --set-advertisement-groups=ALL_SUBNETS \ --set-advertisement-ranges="${PROXY_ONLY_SUBNET_RANGE}" \ --project="${PROJECT_ID}"Verify that Cloud Router is advertising the proxy-only subnet range:
gcloud compute routers describe "${ROUTER_NAME}" \ --region="${REGION}" \ --format="yaml(bgp)" \ --project="${PROJECT_ID}"
Configure firewall policies and on-premises firewall rules
To let traffic flow between the regional internal Application Load Balancer and your on-premises API server, configure both your Google Cloud VPC network firewall policy and your on-premises network firewall.
Configure the Google Cloud VPC network firewall policy
Service Directory private network access sends traffic from 35.199.192.0/19 directly to
the forwarding rule VIP of the regional internal Application Load Balancer, which accepts traffic on
its configured port automatically without requiring a VPC
ingress firewall rule. Because Google Cloud VPC firewall
rules are stateful and distributed Envoy health check probes originate from the
regional proxy-only subnet (PROXY_ONLY_SUBNET_RANGE) toward your on-premises
network, you only need an egress allow rule in your VPC network
firewall policy:
Create a global network firewall policy and associate it with your VPC network:
gcloud compute network-firewall-policies create gecx-onprem-fw-policy \ --global \ --project="${PROJECT_ID}" gcloud compute network-firewall-policies associations create \ --firewall-policy=gecx-onprem-fw-policy \ --name="network-${NETWORK_NAME}" \ --network="${NETWORK_NAME}" \ --global-firewall-policy \ --project="${PROJECT_ID}"Add an egress allow rule permitting outbound requests and distributed Envoy health check probes from the VPC network (including the proxy-only subnet) to your on-premises API subnet:
gcloud compute network-firewall-policies rules create 1000 \ --firewall-policy=gecx-onprem-fw-policy \ --global-firewall-policy \ --direction=EGRESS \ --action=allow \ --dest-ip-ranges="${ON_PREM_CIDR}" \ --layer4-configs="tcp:${ON_PREM_API_PORT}" \ --description="Allow egress from Envoy proxies to on-premises API servers" \ --project="${PROJECT_ID}"
Configure on-premises firewall rules
Work with your on-premises network administrator to confirm that your
on-premises firewall permits the following inbound traffic to your on-premises
API server (ON_PREM_API_IP on port ON_PREM_API_PORT) and DNS infrastructure:
- Source IP range:
PROXY_ONLY_SUBNET_RANGE(for example,10.0.2.0/24). Both load-balanced API requests and distributed Envoy health check probes originate from this range. - Centralized health check ranges (optional):
35.191.0.0/16and130.211.0.0/22, if any centralized Google Cloud health checks are used. - Cloud DNS outbound forwarding range (if using a Cloud DNS
forwarding zone in Option B): Permit inbound UDP and TCP port
53from35.199.192.0/19to your on-premises DNS servers so that Cloud DNS can forward queries for your on-premises domain. - Service Directory private network access range (if routing directly without an
internal Application Load Balancer): If you register an on-premises IP address directly as a
Service Directory endpoint instead of routing through a regional
internal Application Load Balancer, permit inbound TCP traffic on
ON_PREM_API_PORTfrom35.199.192.0/19and advertise35.199.192.0/19using Cloud Router custom route advertisements.
Create the network endpoint group
Complete either Option A (hybrid connectivity NEG) or Option B (regional internet NEG) based on the architectural requirements in Choose a network endpoint group type.
Option A: Create a hybrid connectivity NEG
Use this option when routing directly to static on-premises private IP addresses
(NON_GCP_PRIVATE_IP_PORT).
Create the hybrid connectivity NEG in a zone within the same region as your Cloud VPN tunnel or Cloud Interconnect attachment:
gcloud compute network-endpoint-groups create "${HYBRID_NEG_NAME}" \ --network-endpoint-type=NON_GCP_PRIVATE_IP_PORT \ --zone="${ZONE}" \ --network="${NETWORK_NAME}" \ --project="${PROJECT_ID}"Add your on-premises API server's private IP address and port to the hybrid connectivity NEG:
gcloud compute network-endpoint-groups update "${HYBRID_NEG_NAME}" \ --zone="${ZONE}" \ --add-endpoint="ip=${ON_PREM_API_IP},port=${ON_PREM_API_PORT}" \ --project="${PROJECT_ID}"
Option B: Create a regional internet NEG
Use this option when you require regional NEG availability without a single-zone
dependency, dynamic DNS resolution, or TLS SNI sent to your on-premises backend
(INTERNET_FQDN_PORT).
Create the regional internet NEG in your target region:
gcloud compute network-endpoint-groups create "${INTERNET_NEG_NAME}" \ --network-endpoint-type=INTERNET_FQDN_PORT \ --default-port="${ON_PREM_API_PORT}" \ --network="${NETWORK_NAME}" \ --region="${REGION}" \ --project="${PROJECT_ID}"Add the FQDN and port of your on-premises API server to the regional internet NEG:
gcloud compute network-endpoint-groups update "${INTERNET_NEG_NAME}" \ --region="${REGION}" \ --add-endpoint="fqdn=${FQDN},port=${ON_PREM_API_PORT}" \ --project="${PROJECT_ID}"Configure a Cloud DNS private zone associated with your VPC network so that the Envoy proxies can resolve
FQDN(api.onprem.example.com) to your on-premises private IP address (10.10.100.2):# Create a private Cloud DNS zone visible to your VPC network gcloud dns managed-zones create onprem-private-zone \ --dns-name="onprem.example.com." \ --description="Private zone for on-premises API endpoints" \ --visibility=private \ --networks="${NETWORK_NAME}" \ --project="${PROJECT_ID}" # Add an A record mapping the FQDN to the on-premises API server IP gcloud dns record-sets create "${FQDN}." \ --zone=onprem-private-zone \ --type=A \ --ttl=60 \ --rrdatas="${ON_PREM_API_IP}" \ --project="${PROJECT_ID}"
Configure the regional internal Application Load Balancer
Provision the regional internal Application Load Balancer (INTERNAL_MANAGED) that sits in front of
your NEG and exposes an internal HTTPS endpoint to Service Directory.
Create the health check and backend service
Create a regional HTTPS health check (use
httpif your on-premises API server listens over unencrypted HTTP):gcloud compute health-checks create https "${HEALTH_CHECK_NAME}" \ --region="${REGION}" \ --use-serving-port \ --enable-logging \ --project="${PROJECT_ID}"Create the regional internal managed backend service:
gcloud compute backend-services create "${BACKEND_SERVICE_NAME}" \ --load-balancing-scheme=INTERNAL_MANAGED \ --protocol=HTTPS \ --health-checks="${HEALTH_CHECK_NAME}" \ --health-checks-region="${REGION}" \ --region="${REGION}" \ --project="${PROJECT_ID}"Attach your NEG to the backend service depending on which option you chose in Create the network endpoint group:
If you created a hybrid connectivity NEG (Option A):
gcloud compute backend-services add-backend "${BACKEND_SERVICE_NAME}" \ --region="${REGION}" \ --balancing-mode=RATE \ --max-rate-per-endpoint=100 \ --network-endpoint-group="${HYBRID_NEG_NAME}" \ --network-endpoint-group-zone="${ZONE}" \ --project="${PROJECT_ID}"If you created a regional internet NEG (Option B):
gcloud compute backend-services add-backend "${BACKEND_SERVICE_NAME}" \ --region="${REGION}" \ --network-endpoint-group="${INTERNET_NEG_NAME}" \ --network-endpoint-group-region="${REGION}" \ --project="${PROJECT_ID}"
Create the URL map, TLS certificate, and target HTTPS proxy
CX Agent Studio OpenAPI tools require HTTPS when communicating with a custom TLS certificate over Service Directory.
Create a regional URL map that routes incoming requests to your backend service:
gcloud compute url-maps create "${URL_MAP_NAME}" \ --default-service="${BACKEND_SERVICE_NAME}" \ --region="${REGION}" \ --project="${PROJECT_ID}"Generate a private key and self-signed TLS certificate for
FQDN(api.onprem.example.com), and convert the certificate to DER format (server.der) so that you can upload it to CX Agent Studio:openssl genrsa -out server.key 2048 openssl req -nodes -new -sha256 \ -key server.key \ -subj "/CN=${FQDN}" \ -out server.csr openssl x509 -req -days 3650 -sha256 \ -in server.csr \ -signkey server.key \ -out server.crt \ -extfile <(printf "subjectAltName=DNS:%s\n" "${FQDN}") openssl x509 -in server.crt -out server.der -outform DERCreate a regional self-managed SSL certificate resource in Google Cloud:
gcloud compute ssl-certificates create "${CERTIFICATE_NAME}" \ --certificate=server.crt \ --private-key=server.key \ --region="${REGION}" \ --project="${PROJECT_ID}"Create the regional target HTTPS proxy and attach the SSL certificate and URL map:
gcloud compute target-https-proxies create "${TARGET_PROXY_NAME}" \ --ssl-certificates="${CERTIFICATE_NAME}" \ --url-map="${URL_MAP_NAME}" \ --url-map-region="${REGION}" \ --region="${REGION}" \ --project="${PROJECT_ID}"
Reserve an internal IP address and create the forwarding rule
Reserve a static internal IPv4 address from your load balancer subnet (
LB_SUBNET_NAME):gcloud compute addresses create "${ADDRESS_NAME}" \ --region="${REGION}" \ --subnet="${LB_SUBNET_NAME}" \ --project="${PROJECT_ID}"Store the allocated internal IP address in an environment variable:
export LB_VIP=$(gcloud compute addresses describe "${ADDRESS_NAME}" \ --region="${REGION}" \ --format="value(address)" \ --project="${PROJECT_ID}") echo "Load Balancer Internal VIP: ${LB_VIP}"Create the regional forwarding rule on port
443:gcloud compute forwarding-rules create "${FORWARDING_RULE_NAME}" \ --load-balancing-scheme=INTERNAL_MANAGED \ --network="${NETWORK_NAME}" \ --subnet="${LB_SUBNET_NAME}" \ --address="${ADDRESS_NAME}" \ --ports=443 \ --region="${REGION}" \ --target-https-proxy="${TARGET_PROXY_NAME}" \ --target-https-proxy-region="${REGION}" \ --allow-global-access \ --project="${PROJECT_ID}"
Register the internal load balancer in Service Directory
Register the regional internal Application Load Balancer's VIP (LB_VIP) in Service Directory so
that CX Agent Studio can discover and route to it over private network access.
Create a Service Directory namespace in the same region as your load balancer:
gcloud service-directory namespaces create "${NAMESPACE_NAME}" \ --location="${REGION}" \ --project="${PROJECT_ID}"Create a Service Directory service inside the namespace:
gcloud service-directory services create "${SERVICE_NAME}" \ --namespace="${NAMESPACE_NAME}" \ --location="${REGION}" \ --project="${PROJECT_ID}"Create a Service Directory endpoint pointing to your load balancer's internal IP address (
LB_VIP) and associated with your VPC network:gcloud service-directory endpoints create "${ENDPOINT_NAME}" \ --location="${REGION}" \ --namespace="${NAMESPACE_NAME}" \ --service="${SERVICE_NAME}" \ --address="${LB_VIP}" \ --port=443 \ --network="projects/${PROJECT_NUMBER}/locations/global/networks/${NETWORK_NAME}" \ --project="${PROJECT_ID}"Print the fully qualified Service Directory service path to use in the next section:
echo "projects/${PROJECT_ID}/locations/${REGION}/namespaces/${NAMESPACE_NAME}/services/${SERVICE_NAME}"
Configure CX Agent Studio and the OpenAPI tool
With the Google Cloud networking infrastructure and Service Directory endpoint in place, configure your CX Agent Studio agent and OpenAPI tool.
Create an agent
- Open the CX Agent Studio console.
- Select your Google Cloud project (
PROJECT_ID). - Click Create agent, enter
Order_Status_Agentas the agent name, and click Create.
Create the OpenAPI tool
- In the agent builder navigation bar, click Tools, and then click + (Create) to add a tool.
- Select OpenAPI as the tool type.
- In the Name field, enter
order_status_api. In the Schema (YAML) editor, paste the following OpenAPI 3.0 specification, replacing
api.onprem.example.comwith yourFQDNvalue if you used a different domain in your TLS certificate:openapi: 3.0.0 info: title: On-Premises Order Status API description: Retrieves order fulfillment status from the on-premises API server. version: 1.0.0 servers: - url: https://api.onprem.example.com description: On-premises production API server through regional internal ALB paths: /order/{order_number}: get: summary: Get Order Status description: Returns the current fulfillment status for a specific order number. operationId: getOrderStatus parameters: - name: order_number in: path required: true description: The unique identifier for the order. schema: type: string responses: '200': description: Successful response content: application/json: schema: type: object properties: order_number: type: string status: type: string enum: - pending - processing - shipped - delivered - cancelledExpand the Advanced settings section and configure the private networking fields:
- Custom TLS certificate authorities: Upload the
server.derfile that you generated in Create the URL map, TLS certificate, and target HTTPS proxy. Service Directory: Enter the fully qualified Service Directory service path from Register the internal load balancer in Service Directory:
projects/PROJECT_ID/locations/REGION/namespaces/NAMESPACE_NAME/services/SERVICE_NAMEReplace the following:
PROJECT_ID: your Google Cloud project IDREGION: the region of your Service Directory namespace (for example,us-central1)NAMESPACE_NAME: your Service Directory namespace name (for example,gecx-onprem-ns)SERVICE_NAME: your Service Directory service name (for example,onprem-api-service)
- Custom TLS certificate authorities: Upload the
Click Create.
Attach the tool and configure instructions
- Open the root agent in the agent builder.
- In the Tools section of the agent, click + Add tool and select
order_status_api. In the Instructions section of the root agent, enter the following instructions to invoke the OpenAPI tool when a user asks for an order status:
<role>An order support agent that retrieves real-time order statuses from an on-premises system.</role> <persona> <primary_goal>Ask the user for their order number, invoke the on-premises Order Status tool, and return the status clearly.</primary_goal> </persona> <taskflow> <subtask name="Check Order Status"> <step name="Prompt for Order Number"> <trigger>User asks to check an order status without providing an order number</trigger> <action>Politely ask the user to provide their order number.</action> </step> <step name="Run On-Premises Lookup"> <trigger>User provides an order number</trigger> <action> Immediately call {@TOOL: order_status_api_getOrderStatus} with the provided `order_number`. Return the `order_number` and `status` fields from the JSON payload to the user. </action> </step> </subtask> </taskflow>Click Save.
Test the agent in the simulator
Verify the end-to-end private connection using the built-in simulator in CX Agent Studio:
- In the CX Agent Studio console, click Preview agent to open the simulator pane.
- Enter
Check my order statusand pressEnter. - When prompted for an order number, enter a valid test order ID (for example,
10042) and pressEnter. - Confirm that the agent invokes
order_status_api_getOrderStatus, traverses Service Directory and the regional internal Application Load Balancer over your hybrid connection, and returns the JSON status from your on-premises API server.
Troubleshoot and scale
If your OpenAPI tool calls fail to reach the on-premises server, or if you plan to scale this deployment for production, use the following guidance:
Check Envoy backend health status: Because hybrid connectivity NEGs (
NON_GCP_PRIVATE_IP_PORT) and regional internet NEGs (INTERNET_FQDN_PORT) are health checked directly by distributed Envoy proxies in your proxy-only subnet rather than centralized Google Cloud probers, thegcloud compute backend-services get-healthcommand isn't supported for these backend types. Instead, verify backend health by enabling health check logging (--enable-logging) on your health check and querying Cloud Logging with the following filter:resource.type="gce_network_endpoint_group" log_id("compute.googleapis.com/healthchecks") jsonPayload.healthCheckProbeResult.healthState!=""If the logged
healthStateisUNHEALTHYorTIMEOUT, confirm that Cloud Router is advertisingPROXY_ONLY_SUBNET_RANGEover BGP and that your on-premises firewall permits inbound TCP traffic fromPROXY_ONLY_SUBNET_RANGEtoON_PREM_API_IP:ON_PREM_API_PORT.Monitor Service Directory resolution with Data Access audit logs (
DATA_READ): Service Directory private network access doesn't expose native Cloud Monitoring metrics. To observe service resolution activity and diagnose lookup failures, enable Data Access (DATA_READ) audit logs on the Service Directory API in your Service Directory project, and query Logging with the following filter (you can also create a log-based metric from this query):protoPayload.serviceName="servicedirectory.googleapis.com" protoPayload.methodName="google.cloud.servicedirectory.v1beta1.InternalLookupService.InternalResolveService"Diagnose IAM and VPC Service Controls permission errors:
- Build-time
PERMISSION_DENIEDonservicedirectory.networks.attach: The administrator creating the Service Directory endpoint in Register the internal load balancer in Service Directory is missing the Service Directory Network Attacher (roles/servicedirectory.networkAttacher) role on the project that owns the VPC network (or Shared VPC host project). - Runtime
PERMISSION_DENIEDonservicedirectory.services.resolve: The Customer Engagement Suite service agent (service-WORKLOAD_PROJECT_NUMBER@gcp-sa-ces.iam.gserviceaccount.com) is missingroles/servicedirectory.vieweron the project hosting the Service Directory service. - Runtime
PERMISSION_DENIEDonservicedirectory.networks.access: The Customer Engagement Suite service agent (service-WORKLOAD_PROJECT_NUMBER@gcp-sa-ces.iam.gserviceaccount.com) is missingroles/servicedirectory.pscAuthorizedServiceon the project that owns the VPC network (or Shared VPC host project). - VPC Service Controls perimeter alignment: If your organization uses
VPC Service Controls across split projects, confirm that the
CX Agent Studio workload project, Service Directory project, and
VPC host project belong to the same VPC Service Controls
perimeter, or configure ingress and egress rules permitting
servicedirectory.googleapis.commethods (google.cloud.servicedirectory.v1.RegistrationService.CreateEndpointandgoogle.cloud.servicedirectory.v1beta1.InternalLookupService.InternalResolveService).
- Build-time
Validate Service Directory with a private uptime check: You can configure a Monitoring private uptime check targeting your Service Directory service to independently test TLS handshakes and HTTP status codes before testing from CX Agent Studio.
Scale to multiple on-premises APIs: Although you can configure a separate Service Directory service on each OpenAPI tool or toolset in CX Agent Studio, routing multiple on-premises APIs through a single regional internal Application Load Balancer is recommended as a best practice. You can attach multiple backend services (pointing to different hybrid NEGs or regional internet NEGs) to the same load balancer and configure host and path rules in its URL map (
URL_MAP_NAME) to route requests based on the hostname or URL path in each OpenAPI tool specification.Multi-region deployments and agent-level failover: Service Directory and private network access are regional services. Placing a cross-region internal Application Load Balancer behind a single regional Service Directory service still depends on that single Service Directory region's availability. For end-to-end multi-region high availability, deploy independent regional stacks (Service Directory, regional internal Application Load Balancer, and Cloud VPN or Cloud Interconnect) in at least two regions (for example,
us-central1andus-east1), configure two regional OpenAPI tools on your agent (such asorder_status_api_primaryandorder_status_api_secondary), and instruct the agent to fall back to the secondary regional tool if the primary tool returns a connection or timeout error.
Clean up
To avoid incurring ongoing charges to your Google Cloud account for the resources used in this tutorial, delete the provisioned resources in reverse dependency order.
Delete the CX Agent Studio agent and tool
- Open the CX Agent Studio console and select
your Google Cloud project (
PROJECT_ID). - Select the
Order_Status_Agentagent, open its settings menu, and delete the agent (or remove theorder_status_apiOpenAPI tool if you want to keep the agent).
Delete the Service Directory resources
Deleting the Service Directory namespace automatically deletes all services and endpoints contained within it:
gcloud service-directory namespaces delete "${NAMESPACE_NAME}" \
--location="${REGION}" \
--project="${PROJECT_ID}" \
--quiet
Delete the regional internal Application Load Balancer
Delete the load balancer components in the following order (forwarding rule, reserved internal IP address, target HTTPS proxy, SSL certificate, URL map, backend service, and health check):
# Delete the forwarding rule and reserved internal VIP
gcloud compute forwarding-rules delete "${FORWARDING_RULE_NAME}" \
--region="${REGION}" \
--project="${PROJECT_ID}" \
--quiet
gcloud compute addresses delete "${ADDRESS_NAME}" \
--region="${REGION}" \
--project="${PROJECT_ID}" \
--quiet
# Delete the target HTTPS proxy, SSL certificate, and URL map
gcloud compute target-https-proxies delete "${TARGET_PROXY_NAME}" \
--region="${REGION}" \
--project="${PROJECT_ID}" \
--quiet
gcloud compute ssl-certificates delete "${CERTIFICATE_NAME}" \
--region="${REGION}" \
--project="${PROJECT_ID}" \
--quiet
gcloud compute url-maps delete "${URL_MAP_NAME}" \
--region="${REGION}" \
--project="${PROJECT_ID}" \
--quiet
# Delete the backend service and health check
gcloud compute backend-services delete "${BACKEND_SERVICE_NAME}" \
--region="${REGION}" \
--project="${PROJECT_ID}" \
--quiet
gcloud compute health-checks delete "${HEALTH_CHECK_NAME}" \
--region="${REGION}" \
--project="${PROJECT_ID}" \
--quiet
Delete the network endpoint group and Cloud DNS resources
Delete the NEG resources corresponding to the option you deployed in Create the network endpoint group:
If you created a hybrid connectivity NEG (Option A):
gcloud compute network-endpoint-groups delete "${HYBRID_NEG_NAME}" \ --zone="${ZONE}" \ --project="${PROJECT_ID}" \ --quietIf you created a regional internet NEG and Cloud DNS private zone (Option B):
gcloud compute network-endpoint-groups delete "${INTERNET_NEG_NAME}" \ --region="${REGION}" \ --project="${PROJECT_ID}" \ --quiet gcloud dns record-sets delete "${FQDN}." \ --zone=onprem-private-zone \ --type=A \ --project="${PROJECT_ID}" \ --quiet gcloud dns managed-zones delete onprem-private-zone \ --project="${PROJECT_ID}" \ --quiet
Revert Cloud Router custom route advertisements
Revert your Cloud Router to default route advertisement mode (or remove
${PROXY_ONLY_SUBNET_RANGE} from your custom advertised ranges if you advertise
other custom ranges):
gcloud compute routers update "${ROUTER_NAME}" \
--region="${REGION}" \
--advertisement-mode=DEFAULT \
--project="${PROJECT_ID}"
Delete the firewall policy, subnets, and local files
Remove the network firewall policy association and delete the firewall policy:
gcloud compute network-firewall-policies associations delete \ --firewall-policy=gecx-onprem-fw-policy \ --name="network-${NETWORK_NAME}" \ --global-firewall-policy \ --project="${PROJECT_ID}" gcloud compute network-firewall-policies delete gecx-onprem-fw-policy \ --global \ --project="${PROJECT_ID}" \ --quietDelete the regional proxy-only subnet and load balancer subnet:
gcloud compute networks subnets delete "${PROXY_ONLY_SUBNET_NAME}" \ --region="${REGION}" \ --project="${PROJECT_ID}" \ --quiet gcloud compute networks subnets delete "${LB_SUBNET_NAME}" \ --region="${REGION}" \ --project="${PROJECT_ID}" \ --quietIf you created a new dedicated VPC network for this tutorial, delete the VPC network:
gcloud compute networks delete "${NETWORK_NAME}" \ --project="${PROJECT_ID}" \ --quietRemove the local TLS certificate and private key files from your workstation or Cloud Shell environment:
rm -f server.key server.csr server.crt server.derOptional: If you deployed the sample FastAPI server on your on-premises host, stop and remove the
systemdservice or Docker container, and delete the~/order-status-apidirectory.
What's next
- Follow Connect to an internal Cloud Run service within a VPC Service Controls perimeter to connect CX Agent Studio privately to an internal Cloud Run service over Shared VPC.
- Learn more about setting up an internal Application Load Balancer with hybrid connectivity.
- Learn more about advertising custom IP ranges with Cloud Router.
- Return to the outbound networking overview.