A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://cloud.google.com/sql/docs/postgres/configure-private-service-connect below:

Connect to an instance using Private Service Connect | Cloud SQL for PostgreSQL

Skip to main content Connect to an instance using Private Service Connect

Stay organized with collections Save and categorize content based on your preferences.

This page describes how to use Private Service Connect to connect to a Cloud SQL instance.

You can use Private Service Connect to connect to either a primary Cloud SQL instance or any of its read replicas from multiple Virtual Private Cloud (VPC) networks that belong to different groups, teams, projects, or organizations.

Note: If a Cloud SQL instance has Private Service Connect enabled, then the postgres_fdw, dblink, Pl/Proxy, and pglogical PostgreSQL extensions can't be used with the instance. For more information about these extensions, see Configure PostgreSQL extensions. Before you begin

Support for using Private Service Connect with a Cloud SQL instance is available for gcloud CLI versions 416.0.0 and later.

User roles

The following table provides information about the roles required to use Private Service Connect with a Cloud SQL instance:

Create a Private Service Connect endpoint

Private Service Connect endpoints are internal IP addresses in a consumer VPC network, which clients in that network can access directly. Clients can use these endpoints to connect to Cloud SQL instances.

You can either have Cloud SQL create a Private Service Connect endpoint automatically in your VPC or you can create the endpoint manually.

To have Cloud SQL create the Private Service Connect endpoint automatically, do the following:

  1. Create a service connection policy in your VPC networks. With this policy, you can provision Private Service Connect endpoints automatically.
  2. Create a Cloud SQL instance with Private Service Connect enabled for the instance, and configure the instance to create Private Service Connect endpoints automatically.
  3. Retrieve the endpoint for the instance. This lets you use the endpoint to connect to the instance.

To create the Private Service Connect endpoint manually, do the following:

  1. Create a Cloud SQL instance with Private Service Connect enabled for the instance.
  2. Get the service attachment URI. You use this URI to create the Private Service Connect endpoint.
  3. Reserve an internal IP address for the Private Service Connect endpoint and create an endpoint with that address.
Create the endpoint automatically

Preview

This product is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of the Service Specific Terms. Pre-GA products are available "as is" and might have limited support. For more information, see the launch stage descriptions.

The next few sections explain how to configure your instance to let Cloud SQL create the Private Service Connect endpoint automatically.

Create a service connection policy

A service connection policy lets you authorize a specified service class to create a Private Service Connect endpoint in your consumer VPC network. You can use the service connection policy to let Cloud SQL create Private Service Connect endpoints automatically.

You can create a service connection policy by using the Google Cloud console, gcloud CLI, or the API.

Console
  1. In the Google Cloud console, go to the Private Service Connect page.

    Go to Private Service Connect

  2. Click the Connection Policies tab.

  3. Click Create connection policy.

  4. Enter a Name for the connection policy.

  5. Specify the service class by doing the following:

    1. For Source service class, select Google services.
    2. From the Service class menu, select google-cloud-sql because Cloud SQL is the managed service for the connection policy.
  6. In the Target endpoints scope section, select a Network and Region to which this policy applies.

  7. In the Policy section, select one or more subnets from the Subnetworks menu. The subnets are used to allocate IP addresses for endpoints.

  8. Optional: Specify a Connection limit for the policy. The limit determines how many endpoints can be created by using this connection policy. If you don't specify a connection limit, then there's no limit.

  9. Click Create policy.

gcloud

To create a service connection policy, use the service-connection-policies create command.

gcloud network-connectivity service-connection-policies create POLICY_NAME \
    --network=NETWORK \
    --project=PROJECT_ID \
    --region=REGION \
    --service-class=SERVICE_CLASS \
    --subnets=https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/subnetworks/SUBNETS \
    --psc-connection-limit=LIMIT \
    --description="DESCRIPTION" \
    --producer-instance-location=PRODUCER_INSTANCE_LOCATION \
    --allowed-google-producers-resource-hierarchy-level=RESOURCE_HIERARCHY_LEVEL

Replace the following:

For example, the following command creates a service connection policy for the
google-cloud-sql service class that allocates IP addresses from the managed-services subnet. A maximum of 10 Private Service Connect endpoints can be created by using this policy. The endpoints must be created in projects that are in the same organization as the managed service instance. The Cloud SQL instance is located in the myproject project.

gcloud network-connectivity service-connection-policies create cloud-sql-policy \
    --network=default \
    --project=my-project \
    --region=us-central1 \
    --service-class=google-cloud-sql \
    --subnets=managed-service-subnet \
    --psc-connection-limit=10 \
    --producer-instance-location=custom-resource-hierarchy-levels \
    --allowed-google-producers-resource-hierarchy-level=projects/myproject
REST

Before using any of the request data, make the following replacements:

HTTP method and URL:

POST https://networkconnectivity.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/serviceConnectionPolicies?serviceConnectionPolicyId=POLICY_NAME

Request JSON body:

{
  "description": "DESCRIPTION",
  "network": "projects/PROJECT_ID/global/networks/NETWORK",
  "pscConfig": {
    "limit": "LIMIT",
    "subnetworks": [
      "projects/PROJECT_ID/regions/REGION/subnetworks/SUBNET"
    ]
  },
  "serviceClass": "SERVICE_CLASS"
}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

Save the request body in a file named request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://networkconnectivity.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/serviceConnectionPolicies?serviceConnectionPolicyId=POLICY_NAME"
PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

Save the request body in a file named request.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `


-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://networkconnectivity.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/serviceConnectionPolicies?serviceConnectionPolicyId=POLICY_NAME" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_ID/locations/REGION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.networkconnectivity.v1.OperationMetadata",
    "createTime": "2023-08-15T16:59:29.236110917Z",
    "target": "projects/PROJECT_ID/locations/REGION/serviceConnectionPolicies/POLICY_NAME",
    "verb": "create",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}
Create a Cloud SQL instance

You can create an instance with Private Service Connect enabled for the instance and configure the instance to create endpoints automatically by using gcloud CLI or the API.

Note: After you create the instance, a Private Service Connect endpoint is automatically created in the VPC networks that you specify. However, the endpoint might not be created because of reasons such as the specified network doesn't exist, there's no valid service connection policy, or there aren't any available IP addresses. If this occurs, then the endpoint won't be created. Optionally, you can create Private Service Connect endpoints manually. gcloud

To create an instance with Private Service Connect enabled for the instance, use the gcloud sql instances create command:

gcloud sql instances create INSTANCE_NAME \
--project=PROJECT_ID \
--region=REGION_NAME \
--enable-private-service-connect \
--allowed-psc-projects=ALLOWED_PROJECTS \
--availability-type=AVAILABILITY_TYPE \
--no-assign-ip \
--tier=MACHINE_TYPE \
--database-version=DATABASE_VERSION \
--psc-auto-connections=network=CONSUMER_NETWORK,project=CONSUMER_PROJECT

Make the following replacements:

REST

Before using any of the request data, make the following replacements:

HTTP method and URL:

POST https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances

Request JSON body:

{
  "name": "INSTANCE_NAME",
  "project": PROJECT_ID",
  "region": "REGION_NAME",
  "databaseVersion": "POSTGRES_13",
  "kind": "sql#instance",
  "settings": {
    "availabilityType": "AVAILABILITY_TYPE",
    "ipConfiguration": {
      "ipv4Enabled": false,
      "pscConfig": {
        "allowedConsumerProjects": [
          "ALLOWED_PROJECTS"
        ],
        "pscAutoConnections": [
          {
            "consumerProject":"CONSUMER_PROJECT",
            "consumerNetwork":"projects/PARENT_PROJECT/global/networks/CONSUMER_NETWORK"
          }
        ],
        "pscEnabled": true
      }
    },
    "kind": "sql#settings",
    "pricingPlan": "PER_USE",
    "replicationType": "SYNCHRONOUS",
    "tier": "MACHINE_TYPE"
  }
}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

Save the request body in a file named request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances"
PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

Save the request body in a file named request.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `


-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "kind": "sql#operation",
  "targetLink": "https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_NAME",
  "status": "RUNNING",
  "user": "user@example.com",
  "insertTime": "2020-01-16T02:32:12.281Z",
  "startTime": "2023-06-14T18:48:35.499Z",
  "operationType": "CREATE",
  "name": "OPERATION_ID",
  "targetId": "INSTANCE_NAME",
  "selfLink": "https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/operations/OPERATION_ID",
  "targetProject": "PROJECT_ID"
}
Retrieve the endpoint

By retrieving the internal IP address, which is the Private Service Connect endpoint for an instance, you can use this endpoint to connect to the instance.

gcloud

To view information about an instance, including the IP address that's the Private Service Connect endpoint for the instance, use the gcloud sql instances describe command:

gcloud sql instances describe INSTANCE_NAME \
--project=PROJECT_ID \
--format='json(settings.ipConfiguration.pscConfig.pscAutoConnections)'

Make the following replacements:

In the response, note the value that appears next to the pscConfig:pscAutoConnections:ipAddress field. This value is the internal IP address that's also the Private Service Connect endpoint for the instance.

REST

Before using any of the request data, make the following replacements:

HTTP method and URL:

GET https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_NAME

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

Execute the following command:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_NAME"
PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

Execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `


-Method GET `
-Headers $headers `
-Uri "https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_NAME" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "kind": "sql#instance",
  "state": "RUNNABLE",
  "databaseVersion": "POSTGRES_13",
  "settings": {
    "authorizedGaeApplications": [],
    "tier": "db-custom-2-7680",
    "kind": "sql#settings",
    "availabilityType": "REGIONAL",
    "pricingPlan": "PER_USE",
    "replicationType": "SYNCHRONOUS",
    "activationPolicy": "ALWAYS",
    "ipConfiguration": {
      "authorizedNetworks": [],
      "pscConfig": {
        "allowedConsumerProjects": [
          "ALLOWED_PROJECTS"
        ],
      "pscAutoConnections": {
        consumerNetwork:"projects/PARENT_PROJECT/global/networks/CONSUMER_NETWORK",
        consumerNetworkStatus:"CONSUMER_NETWORK_STATUS",
        consumerProject:"CONSUMER_PROJECT",
        ipAddress:"IP_ADDRESS",
        status:"STATUS"
        },
        "pscEnabled": true
      },
      "ipv4Enabled": false
    },
}

The following fields exist for instances that have Private Service Connect enabled for them:

To see how to construct the underlying REST API request for this task, see the instances:get page.

Create the endpoint manually

The next few sections explain how to create a Private Service Connect endpoint manually.

Create a Cloud SQL instance

You can create an instance with Private Service Connect enabled for the instance by using gcloud CLI, Terraform, or the API.

Note: You can now create an instance that supports both private services access and Private Service Connect. By using Private Service Connect, you can connect to either a primary instance or any of its read replicas from multiple VPC networks. For more information, see Configure both private services access and Private Service Connect.

gcloud

To create an instance with Private Service Connect enabled for the instance, use the gcloud sql instances create command:

gcloud sql instances create INSTANCE_NAME \
--project=PROJECT_ID \
--region=REGION_NAME \
--enable-private-service-connect \
--allowed-psc-projects=ALLOWED_PROJECTS \
--availability-type=AVAILABILITY_TYPE \
--no-assign-ip \
--tier=MACHINE_TYPE \
--database-version=DATABASE_VERSION

Make the following replacements:

Terraform

To create an instance with Private Service Connect enabled for the instance, use the google_sql_database_instanceTerraform resource.

To apply your Terraform configuration in a Google Cloud project, complete the steps in the following sections.

Prepare Cloud Shell
  1. Launch Cloud Shell.
  2. Set the default Google Cloud project where you want to apply your Terraform configurations.

    You only need to run this command once per project, and you can run it in any directory.

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    Environment variables are overridden if you set explicit values in the Terraform configuration file.

Prepare the directory

Each Terraform configuration file must have its own directory (also called a root module).

  1. In Cloud Shell, create a directory and a new file within that directory. The filename must have the .tf extension—for example main.tf. In this tutorial, the file is referred to as main.tf.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. If you are following a tutorial, you can copy the sample code in each section or step.

    Copy the sample code into the newly created main.tf.

    Optionally, copy the code from GitHub. This is recommended when the Terraform snippet is part of an end-to-end solution.

  3. Review and modify the sample parameters to apply to your environment.
  4. Save your changes.
  5. Initialize Terraform. You only need to do this once per directory.
    terraform init

    Optionally, to use the latest Google provider version, include the -upgrade option:

    terraform init -upgrade
Apply the changes
  1. Review the configuration and verify that the resources that Terraform is going to create or update match your expectations:
    terraform plan

    Make corrections to the configuration as necessary.

  2. Apply the Terraform configuration by running the following command and entering yes at the prompt:
    terraform apply

    Wait until Terraform displays the "Apply complete!" message.

  3. Open your Google Cloud project to view the results. In the Google Cloud console, navigate to your resources in the UI to make sure that Terraform has created or updated them.
Note: Terraform samples typically assume that the required APIs are enabled in your Google Cloud project. REST

Before using any of the request data, make the following replacements:

HTTP method and URL:

POST https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances

Request JSON body:

{
  "name": "INSTANCE_NAME",
  "project": PROJECT_ID",
  "region": "REGION_NAME",
  "databaseVersion": "POSTGRES_13",
  "kind": "sql#instance",
  "settings": {
    "availabilityType": "AVAILABILITY_TYPE",
    "ipConfiguration": {
      "ipv4Enabled": false,
      "pscConfig": {
        "allowedConsumerProjects": [
          "ALLOWED_PROJECTS"
        ],
        "pscEnabled": true
      }
    },
    "kind": "sql#settings",
    "pricingPlan": "PER_USE",
    "replicationType": "SYNCHRONOUS",
    "tier": "MACHINE_TYPE"
  }
}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

Save the request body in a file named request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances"
PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

Save the request body in a file named request.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `


-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "kind": "sql#operation",
  "targetLink": "https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_NAME",
  "status": "RUNNING",
  "user": "user@example.com",
  "insertTime": "2020-01-16T02:32:12.281Z",
  "startTime": "2023-06-14T18:48:35.499Z",
  "operationType": "CREATE",
  "name": "OPERATION_ID",
  "targetId": "INSTANCE_NAME",
  "selfLink": "https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/operations/OPERATION_ID",
  "targetProject": "PROJECT_ID"
}
Get the service attachment

After creating a Cloud SQL instance with Private Service Connect enabled, get the service attachment URI and use it to create the Private Service Connect endpoint.

gcloud

To view summary information about an instance with Private Service Connect enabled, such as the pscServiceAttachmentLink field which displays the URI that points to the service attachment of the instance, use the gcloud sql instances describe command:

gcloud sql instances describe INSTANCE_NAME \
--project=PROJECT_ID

Note: The service attachment URI is used to create the Private Service Connect endpoint.

Make the following replacements:

The following example shows a sample output for this command:

gcloud sql instances describe myinstance \
--project=12345

...
pscServiceAttachmentLink: projects/45678/regions/myregion/serviceAttachments/myserviceattachment
Terraform

To get the service attachment URI, use the google_compute_addressTerraform resource.

To apply your Terraform configuration in a Google Cloud project, complete the steps in the following sections.

Prepare Cloud Shell
  1. Launch Cloud Shell.
  2. Set the default Google Cloud project where you want to apply your Terraform configurations.

    You only need to run this command once per project, and you can run it in any directory.

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    Environment variables are overridden if you set explicit values in the Terraform configuration file.

Prepare the directory

Each Terraform configuration file must have its own directory (also called a root module).

  1. In Cloud Shell, create a directory and a new file within that directory. The filename must have the .tf extension—for example main.tf. In this tutorial, the file is referred to as main.tf.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. If you are following a tutorial, you can copy the sample code in each section or step.

    Copy the sample code into the newly created main.tf.

    Optionally, copy the code from GitHub. This is recommended when the Terraform snippet is part of an end-to-end solution.

  3. Review and modify the sample parameters to apply to your environment.
  4. Save your changes.
  5. Initialize Terraform. You only need to do this once per directory.
    terraform init

    Optionally, to use the latest Google provider version, include the -upgrade option:

    terraform init -upgrade
Apply the changes
  1. Review the configuration and verify that the resources that Terraform is going to create or update match your expectations:
    terraform plan

    Make corrections to the configuration as necessary.

  2. Apply the Terraform configuration by running the following command and entering yes at the prompt:
    terraform apply

    Wait until Terraform displays the "Apply complete!" message.

  3. Open your Google Cloud project to view the results. In the Google Cloud console, navigate to your resources in the UI to make sure that Terraform has created or updated them.
Note: Terraform samples typically assume that the required APIs are enabled in your Google Cloud project. REST

Before using any of the request data, make the following replacements:

HTTP method and URL:

GET https://sqladmin.googleapis.com/sql/v1/projects/PROJECT_ID/instances/INSTANCE_NAME

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

Execute the following command:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://sqladmin.googleapis.com/sql/v1/projects/PROJECT_ID/instances/INSTANCE_NAME"
PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

Execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `


-Method GET `
-Headers $headers `
-Uri "https://sqladmin.googleapis.com/sql/v1/projects/PROJECT_ID/instances/INSTANCE_NAME" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  ...
  pscServiceAttachmentLink: "projects/PROJECT_ID/regions/REGION_NAME/serviceAttachments/SERVICE_ATTACHMENT_NAME"
}

The pscServiceAttachmentLink field displays the URI that points to the service attachment of the instance.

Create a Private Service Connect endpoint

You can reserve an internal IP address for the Private Service Connect endpoint and create an endpoint with that address. To create the endpoint, you need the service attachment URI and the projects that are allowed for the instance.

gcloud
  1. To reserve an internal IP address for the Private Service Connect endpoint, use the
    gcloud compute addresses create command:

    gcloud compute addresses create ADDRESS_NAME \
    --project=PROJECT_ID \
    --region=REGION_NAME \
    --subnet=SUBNET_URI \
    --addresses=INTERNAL_IP_ADDRESS

    Make the following replacements:

  2. To verify that the IP address is reserved, use the gcloud compute addresses list command:

    gcloud compute addresses list ADDRESS_NAME \
    --project=PROJECT_ID

    In the response, verify that a RESERVED status appears for the IP address.

  3. To create the Private Service Connect endpoint and point it to the Cloud SQL service attachment, use the gcloud compute forwarding-rules create command:

    gcloud compute forwarding-rules create ENDPOINT_NAME \
    --address=ADDRESS_NAME \
    --project=PROJECT_ID \
    --region=REGION_NAME \
    --network=NETWORK_URI \
    --target-service-attachment=SERVICE_ATTACHMENT_URI \
    --allow-psc-global-access

    Make the following replacements:

    By using the optional --allow-psc-global-access parameter, clients from all regions can access this forwarding rule.
  4. To verify that the service attachment accepts the endpoint, use the
    gcloud compute forwarding-rules describe command:

    gcloud compute forwarding-rules describe ENDPOINT_NAME \
    --project=PROJECT_ID \
    --region=REGION_NAME

    In the response, verify that an ACCEPTED status appears for the pscConnectionStatus field. The endpoint can connect to the service attachment.

Terraform

To create a Private Service Connect endpoint, use the google_sql_database_instanceTerraform resource.

To apply your Terraform configuration in a Google Cloud project, complete the steps in the following sections.

Prepare Cloud Shell
  1. Launch Cloud Shell.
  2. Set the default Google Cloud project where you want to apply your Terraform configurations.

    You only need to run this command once per project, and you can run it in any directory.

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    Environment variables are overridden if you set explicit values in the Terraform configuration file.

Prepare the directory

Each Terraform configuration file must have its own directory (also called a root module).

  1. In Cloud Shell, create a directory and a new file within that directory. The filename must have the .tf extension—for example main.tf. In this tutorial, the file is referred to as main.tf.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. If you are following a tutorial, you can copy the sample code in each section or step.

    Copy the sample code into the newly created main.tf.

    Optionally, copy the code from GitHub. This is recommended when the Terraform snippet is part of an end-to-end solution.

  3. Review and modify the sample parameters to apply to your environment.
  4. Save your changes.
  5. Initialize Terraform. You only need to do this once per directory.
    terraform init

    Optionally, to use the latest Google provider version, include the -upgrade option:

    terraform init -upgrade
Apply the changes
  1. Review the configuration and verify that the resources that Terraform is going to create or update match your expectations:
    terraform plan

    Make corrections to the configuration as necessary.

  2. Apply the Terraform configuration by running the following command and entering yes at the prompt:
    terraform apply

    Wait until Terraform displays the "Apply complete!" message.

  3. Open your Google Cloud project to view the results. In the Google Cloud console, navigate to your resources in the UI to make sure that Terraform has created or updated them.
Note: Terraform samples typically assume that the required APIs are enabled in your Google Cloud project. REST
  1. Reserve an internal IP address for the Private Service Connect endpoint.

    Note: You can't use the API to reserve an internal IP address for the endpoint. To reserve this address, use the gcloud compute addresses create command.
  2. Verify that the IP address is reserved.

    Before using any of the request data, make the following replacements:

    HTTP method and URL:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/addresses/ADDRESS_NAME

    To send your request, expand one of these options:

    curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/addresses/ADDRESS_NAME"
    PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `


    -Method GET `
    -Headers $headers `
    -Uri "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/addresses/ADDRESS_NAME" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    {
      "kind": "compute#address",
      "id": "ADDRESS_ID",
      "creationTimestamp": "2024-05-09T11:20:50.114-07:00",
      "name": "ADDRESS_NAME",
      "description": "This is the name of the internal IP address.",
      "address": "IP_ADDRESS",
      "status": "RESERVED",
      "region": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME",
      "selfLink": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/addresses/ADDRESS_NAME",
      "networkTier": "PREMIUM",
      "labelFingerprint": "LABEL_FINGERPRINT_ID",
      "addressType": "EXTERNAL"
    }
    

    In the response, verify that a RESERVED status appears for the IP address.

  3. Create the Private Service Connect endpoint and point it to the Cloud SQL service attachment.

    Note: You can't use the API to create the Private Service Connect endpoint. To create this endpoint, use the gcloud compute forwarding-rules create command.
  4. Verify that the service attachment accepts the endpoint.

    Before using any of the request data, make the following replacements:

    HTTP method and URL:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules/ENDPOINT_NAME

    To send your request, expand one of these options:

    curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules/ENDPOINT_NAME"
    PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `


    -Method GET `
    -Headers $headers `
    -Uri "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules/ENDPOINT_NAME" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    {
      "kind": "compute#forwardingRule",
      "id": "ENDPOINT_ID",
      "creationTimestamp": "2024-05-09T12:03:21.383-07:00",
      "name": "ENDPOINT_NAME",
      "region": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME",
      "IPAddress": "IP_ADDRESS",
      "target": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/serviceAttachments/SERVICE_ATTACHMENT_NAME",
      "selfLink": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules/ENDPOINT_NAME",
      "network": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/default",
      "serviceDirectoryRegistrations": [
        {
          "namespace": "goog-psc-default"
        }
      ],
      "networkTier": "PREMIUM",
      "labelFingerprint": "LABEL_FINGERPRINT_ID",
      "fingerprint": "FINGERPRINT_ID",
      "pscConnectionId": "CONNECTION_ID",
      "pscConnectionStatus": "ACCEPTED",
      "allowPscGlobalAccess": true
    }
    

    In the response, verify that an ACCEPTED status appears for the pscConnectionStatus field. The endpoint can connect to the service attachment.

Connect to a Cloud SQL instance

You can connect to a Cloud SQL instance with Private Service Connect enabled by using an internal IP address, a DNS record, the Cloud SQL Auth Proxy, the Cloud SQL Language Connectors, or other Google Cloud applications.

Configure a DNS managed zone and a DNS record

Cloud SQL doesn't create DNS records automatically. Instead, the instance lookup API response provides a suggested DNS name. We recommend that you create the DNS record in a private DNS zone in the corresponding VPC network. This provides a consistent way of using the Cloud SQL Auth Proxy to connect from different networks.

Important: If you're using the Cloud SQL Auth Proxy or the Cloud SQL Language Connectors, then set up a DNS record which matches the recommended DNS name provided for the instance. For more information, see Connect using the Cloud SQL Auth Proxy.

For more information about best practices for private DNS zones, including how to allow on-premises hosts to query DNS records that are hosted in these zones, see Best practices for Cloud DNS private zones.

gcloud
  1. To view summary information about a Cloud SQL instance, including the DNS name of the instance, use the gcloud sql instances describe command:

    gcloud sql instances describe INSTANCE_NAME \
    --project=PROJECT_ID

    Make the following replacements:

    In the response, verify that the DNS name appears. This name has the following pattern: INSTANCE_UID.PROJECT_DNS_LABEL.REGION_NAME.sql.goog.. For example: 1a23b4cd5e67.1a2b345c6d27.us-central1.sql.goog..

    Note: DNS names always end with a period (.).

    If you want to use a custom DNS name to connect to a Cloud SQL instance instead of using the predefined DNS name in this section, then configure the custom subject alternative name (SAN) setting while creating the instance. The custom DNS name that you insert into the custom SAN setting is added to the SAN field of the server certificate of the instance. This lets you use the custom DNS name with hostname validation securely.

    For more information about configuring the custom SAN setting, see Create instances.

  2. To create a private DNS zone, use the gcloud dns managed-zones create command. This zone is associated with the VPC network that's used to connect to the Cloud SQL instance through the Private Service Connect endpoint.

    Note: For each VPC network, create a DNS zone.

    gcloud dns managed-zones create ZONE_NAME \
    --project=PROJECT_ID \
    --description="DESCRIPTION" \
    --dns-name=DNS_NAME \
    --networks=NETWORK_NAME \
    --visibility=private

    Make the following replacements:

  3. After you create the Private Service Connect endpoint, to create a DNS record in the zone, use the gcloud dns record-sets create command:

    gcloud dns record-sets create DNS_RECORD \
    --project=PROJECT_ID \
    --type=RRSET_TYPE \
    --rrdatas=RR_DATA \
    --zone=ZONE_NAME

    Make the following replacements:

REST
  1. Get the DNS name of a Cloud SQL instance.
  2. Before using any of the request data, make the following replacements:

    HTTP method and URL:

    GET https://sqladmin.googleapis.com/sql/v1/projects/PROJECT_ID/instances/INSTANCE_NAME

    To send your request, expand one of these options:

    curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://sqladmin.googleapis.com/sql/v1/projects/PROJECT_ID/instances/INSTANCE_NAME"
    PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `


    -Method GET `
    -Headers $headers `
    -Uri "https://sqladmin.googleapis.com/sql/v1/projects/PROJECT_ID/instances/INSTANCE_NAME" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    {
      ...
      "dnsName": "INSTANCE_ID.PROJECT_DNS_LABEL.REGION_NAME.sql.goog."
    }
    

    The dnsName field displays the DNS name of the Cloud SQL instance. DNS names always end with a period (.).

  3. Create a private DNS zone. This zone is associated with the VPC network that's used to connect to the Cloud SQL instance through the Private Service Connect endpoint.
  4. Note: For each VPC network, create a DNS zone.

    Before using any of the request data, make the following replacements:

    HTTP method and URL:

    POST https://dns.googleapis.com/dns/v1/projects/PROJECT_ID/managedZones

    Request JSON body:

    {
      "name": "ZONE_NAME",
      "description": "DESCRIPTION",
      "dnsName": "DNS_NAME",
      "visibility": "private",
      "privateVisibilityConfig": {
        "kind": "dns#managedZonePrivateVisibilityConfig",
        "networks": [
          {
            "kind": "dns#managedZonePrivateVisibilityConfigNetwork",
            "networkUrl": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/NETWORK_NAME"
          }
        ]
      }
    }
    

    To send your request, expand one of these options:

    curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

    Save the request body in a file named request.json, and execute the following command:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://dns.googleapis.com/dns/v1/projects/PROJECT_ID/managedZones"
    PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

    Save the request body in a file named request.json, and execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `


    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://dns.googleapis.com/dns/v1/projects/PROJECT_ID/managedZones" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    {
      "name": "ZONE_NAME",
      "dnsName": "DNS_NAME",
      "description": "DESCRIPTION",
      "id": "ID",
      "nameServers": [
        "ns-gcp-private.googledomains.com."
      ],
      "creationTime": "2024-05-10T17:05:34.607Z",
      "visibility": "private",
      "privateVisibilityConfig": {
        "networks": [
          {
            "networkUrl": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/NETWORK_NAME",
            "kind": "dns#managedZonePrivateVisibilityConfigNetwork"
          }
        ],
        "gkeClusters": [],
        "kind": "dns#managedZonePrivateVisibilityConfig"
      },
      "cloudLoggingConfig": {
        "kind": "dns#managedZoneCloudLoggingConfig"
      },
      "kind": "dns#managedZone"
    }
    
  5. After you create the Private Service Connect endpoint, create a DNS record in the zone.
  6. Before using any of the request data, make the following replacements:

    HTTP method and URL:

    POST https://dns.googleapis.com/dns/v1/projects/PROJECT_ID/managedZones/ZONE_NAME

    Request JSON body:

    {
      "deletions": []
      "additions": [
        {
          "name": "DNS_RECORD",
          "type": "RRSET_TYPE",
          "ttl": TTL,
          "rrdatas": [
            "RR_DATA"
          ]
        }
      ]
    }
    

    To send your request, expand one of these options:

    curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

    Save the request body in a file named request.json, and execute the following command:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://dns.googleapis.com/dns/v1/projects/PROJECT_ID/managedZones/ZONE_NAME"
    PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

    Save the request body in a file named request.json, and execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `


    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://dns.googleapis.com/dns/v1/projects/PROJECT_ID/managedZones/ZONE_NAME" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    {
      "additions": [
        {
          "name": "DNS_RECORD",
          "type": "RRSET_TYPE",
          "ttl": TTL,
          "rrdatas": [
            "RR_DATA"
          ],
          "signatureRrdatas": [],
          "kind": "dns#resourceRecordSet"
        }
      ],
      "deletions": [],
      "startTime": "2024-05-10T17:29:44.375Z",
      "id": "CHANGE_ID",
      "status": "pending",
      "kind": "dns#change"
    }
    
    Note: If you're using this DNS record to connect to the Cloud SQL instance, then make a note of the CHANGE_ID value.
Connect directly using a DNS record

Before connecting to a Cloud SQL instance using a DNS record, do the following:

  1. Create a Private Service Connect endpoint.
  2. Confirm that the service attachment of the instance accepts the endpoint. To verify that the status of the endpoint is ACCEPTED, check the status.
  3. Configure a DNS managed zone and a DNS record.

After you meet these conditions, use the DNS record to connect to the instance from any VPC network where you created the endpoint.

psql "sslmode=disable dbname=DATABASE_NAME user=USERNAME host=DNS_RECORD"

Make the following replacements:

Connect directly through an internal IP address

Before connecting to a Cloud SQL instance with Private Service Connect enabled, do the following:

  1. Create a Private Service Connect endpoint.
  2. Confirm that the service attachment of the instance accepts the endpoint. To verify that the status of the endpoint is ACCEPTED, check the status.

After you meet these conditions, use the endpoint's IP address to access the instance from any VPC network where you created the endpoint.

  1. Retrieve the internal IP address of the Private Service Connect endpoint using the name of the endpoint's IP address.

    Note: You can use the commands in this section to retrieve the internal IP addresses of all endpoints that are created both manaully and automatically. To retrieve the internal IP addresses of endpoints that are created automatically, see Retrieve the endpoint. gcloud

    To retrieve the IP address, use the gcloud compute addresses describe command:

    gcloud compute addresses describe ADDRESS_NAME \
    --project=PROJECT_ID \
    --region=REGION_NAME

    Make the following replacements:

    In the response, verify that an IP address appears for the address field. This is the internal IP address.

    REST

    Before using any of the request data, make the following replacements:

    HTTP method and URL:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/addresses/ADDRESS_NAME

    To send your request, expand one of these options:

    curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/addresses/ADDRESS_NAME"
    PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `


    -Method GET `
    -Headers $headers `
    -Uri "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/addresses/ADDRESS_NAME" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    {
      "kind": "compute#address",
      "id": "ADDRESS_ID",
      "creationTimestamp": "2024-05-09T11:20:50.114-07:00",
      "name": "ADDRESS_NAME",
      "description": "This is the name of the internal IP address.",
      "address": "IP_ADDRESS",
      "status": "RESERVED",
      "region": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME",
      "selfLink": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/addresses/ADDRESS_NAME",
      "networkTier": "PREMIUM",
      "labelFingerprint": "LABEL_FINGERPRINT_ID",
      "addressType": "EXTERNAL"
    }
    

    The internal IP address is the value that's associated with the address field.

  2. Alternatively, retrieve the internal IP address of the Private Service Connect endpoint using the service attachment of the Cloud SQL instance.

    gcloud

    To retrieve the IP address, use the gcloud compute forwarding-rules list command:

    gcloud compute forwarding-rules list \
    --filter="TARGET:REGION_NAME/serviceAttachments/SERVICE_ATTACHMENT_NAME" \
    --project=PROJECT_ID

    Make the following replacements:

    In the response, verify that an IP address appears. This is the internal IP address.

    The following is a sample response:

    NAME REGION IP_ADDRESS TARGET myInstance us-central1 10.10.10.10 us-central1/serviceAttachments/a-123456789e0a-psc-service-attachment-abc123d4e5f67gh8 REST

    Before using any of the request data, make the following replacements:

    HTTP method and URL:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules?target="https://www.googleapis.com/compute/v1/projects/SERVICE_ATTACHMENT_PROJECT_ID/regions/REGION_NAME/serviceAttachments/SERVICE_ATTACHMENT_NAME"

    To send your request, expand one of these options:

    curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules?target="https://www.googleapis.com/compute/v1/projects/SERVICE_ATTACHMENT_PROJECT_ID/regions/REGION_NAME/serviceAttachments/SERVICE_ATTACHMENT_NAME""
    PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `


    -Method GET `
    -Headers $headers `
    -Uri "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules?target="https://www.googleapis.com/compute/v1/projects/SERVICE_ATTACHMENT_PROJECT_ID/regions/REGION_NAME/serviceAttachments/SERVICE_ATTACHMENT_NAME"" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    {
      "kind": "compute#forwardingRuleList",
      "id": "projects/PROJECT_ID/regions/REGION_NAME/forwardingRules",
      "items": [
        {
          "kind": "compute#forwardingRule",
          "id": "FORWARDING_RULE_ID",
          "creationTimestamp": "2023-10-31T13:04:37.168-07:00",
          "name": "FORWARDING_RULE_NAME",
          "region": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME",
          "IPAddress": "IP_ADDRESS",
          "target": "https://www.googleapis.com/compute/v1/projects/SERVICE_ATTACHMENT_PROJECT_ID/regions/REGION_NAME/serviceAttachments/SERVICE_ATTACHMENT_NAME",
          "selfLink": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules/FORWARDING_RULE_NAME",
          "network": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/VPC_NETWORK_NAME",
          "serviceDirectoryRegistrations": [
            {
              "namespace": "goog-psc-default"
            }
          ],
          "networkTier": "PREMIUM",
          "labelFingerprint": "LABEL_FINGERPRINT_ID",
          "fingerprint": "FINGERPRINT_ID",
          "pscConnectionId": "PSC_CONNECTION_ID",
          "pscConnectionStatus": "CLOSED",
          "allowPscGlobalAccess": true
        }
      ],
      "selfLink": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules"
    }
    

    The internal IP address is the value that's associated with the IPAddress field.

  3. To connect to the Cloud SQL instance, use the internal IP address.

    psql "sslmode=disable dbname=DATABASE_NAME user=USERNAME hostaddr=IP_ADDRESS"

    Make the following replacements:

Connect using the Cloud SQL Auth Proxy

The Cloud SQL Auth Proxy is a connector that provides secure access to an instance with Private Service Connect enabled without a need for authorized networks or for configuring SSL.

To allow Cloud SQL Auth Proxy client connections, set up a DNS record which matches the recommended DNS name that's provided for the instance. The DNS record is a mapping between a DNS resource and a domain name.

If you're connecting through Private Service Connect, then Cloud SQL Auth Proxy version v2.5.0 or later is required.

Download and install the Cloud SQL Auth Proxy

To connect to instances with Private Service Connect enabled, you must download and install the binary for the Cloud SQL Auth Proxy. The binary that you download depends on the operating system, and whether it uses a 32-bit or 64-bit kernel. Most newer hardware uses a 64-bit kernel.

If you're unsure whether your machine is running a 32-bit or 64-bit kernel, then use the uname -a command for Linux or macOS. For Windows, see the Windows documentation.

Start the Cloud SQL Auth Proxy

The Cloud SQL Auth Proxy supports connections to instances with Private Service Connect enabled. For more information, see Start the Cloud SQL Auth Proxy.

  1. View summary information about a Cloud SQL instance, including the connection name of the instance. gcloud

    To view summary information about a Cloud SQL instance, use the
    gcloud sql instances describe command.

    gcloud sql instances describe INSTANCE_NAME \
    --project=PROJECT_ID \
    --format='value(connectionName)'

    Make the following replacements:

    The connection name is in the format of PROJECT_ID:REGION_NAME:INSTANCE_NAME.

    REST

    Before using any of the request data, make the following replacements:

    HTTP method and URL:

    GET https://sqladmin.googleapis.com/sql/v1/projects/PROJECT_ID/instances/INSTANCE_NAME

    To send your request, expand one of these options:

    curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://sqladmin.googleapis.com/sql/v1/projects/PROJECT_ID/instances/INSTANCE_NAME"
    PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `


    -Method GET `
    -Headers $headers `
    -Uri "https://sqladmin.googleapis.com/sql/v1/projects/PROJECT_ID/instances/INSTANCE_NAME" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    {
      ...
      "connectionName": "PROJECT_ID:REGION_NAME:INSTANCE_NAME"
    }
    

    The connection name is in the format of PROJECT_ID:REGION_NAME:INSTANCE_NAME.

  2. Copy the instance connection name.
  3. Launch the Cloud SQL Auth Proxy:

    ./cloud-sql-proxy INSTANCE_CONNECTION_NAME --psc 

    Replace INSTANCE_CONNECTION_NAME with the instance connection name that you copied in the previous step.

    Note: Use the psc flag to start the Cloud SQL Auth Proxy to connect to instances with Private Service Connect enabled.

Connect using the Cloud SQL Language Connectors

The Cloud SQL Language Connectors are libraries that provide secure access to a Cloud SQL instance with Private Service Connect enabled without a need for authorized networks or for configuring SSL.

To allow connections with Cloud SQL Language Connectors, set up a DNS record which matches the recommended DNS name that's provided for the instance. The DNS record is a mapping between a DNS resource and a domain name.

The Cloud SQL Language Connectors support Private Service Connect connections through the PSC IP type within their respective libraries.

Connect from App Engine Standard, Cloud Run, or Cloud Run functions

To connect to Cloud SQL instances with Private Service Connect enabled, you can use App Engine Standard or Cloud Run.

In these supported serverless environments, both the Cloud SQL Language Connectors and direct TCP connections by using an IP address and port number are supported. For direct TCP connections, this is the IP address that you reserve when you create the Private Service Connect endpoint. You can specify the IP address as the address for the database host.

If you create a DNS record for the endpoint, then you can specify this record for the host.

Connect from BigQuery

To access data in Cloud SQL and make queries against this data over an internal IP connection, use the
--enable-google-private-path parameter . This parameter is valid only if:

Test connectivity

To test inbound connectivity to a Cloud SQL instance with Private Service Connect enabled, set the IP address of the Private Service Connect endpoint to be the destination IP address.

gcloud

To create a connectivity test for a Cloud SQL instance with Private Service Connect enabled, use the gcloud network-management connectivity-tests create command:

gcloud network-management connectivity-tests create CONNECTIVITY_TEST_NAME \
--source-instance=SOURCE_INSTANCE \
--destination-cloud-sql-instance=DESTINATION_CLOUD_SQL_INSTANCE \
--destination-network=DESTINATION_NETWORK \
--destination-port=DESTINATION_PORT \
--protocol=tcp

Make the following replacements:

REST

Before using any of the request data, make the following replacements:

HTTP method and URL:

POST https://networkmanagement.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/connectivityTests?testId=CONNECTIVITY_TEST_NAME

Request JSON body:

{
  "source": {
    "ipAddress": "SOURCE_IP_ADDRESS",
    "instance": "SOURCE_INSTANCE",
    "network": "SOURCE_NETWORK"
  },
  "destination": {
    "ipAddress": "DESTINATION_IP_ADDRESS",
    "port": DESTINATION_PORT,
    "network": "DESTINATION_NETWORK",
    "projectId": "PROJECT_ID"
  },
  "protocol": "TCP"
}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

Save the request body in a file named request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://networkmanagement.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/connectivityTests?testId=CONNECTIVITY_TEST_NAME"
PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

Save the request body in a file named request.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `


-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://networkmanagement.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/connectivityTests?testId=CONNECTIVITY_TEST_NAME" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_ID/locations/global/operations/operation-OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.networkmanagement.v1.OperationMetadata",
    "createTime": "2024-05-23T16:43:49.313981473Z",
    "target": "projects/PROJECT_ID/locations/global/connectivityTests/CONNECTIVITY_TEST_NAME",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
Note: In addition to testing connectivity, you can restrict connectivity to Private Service Connect endpoints from service consumers in a VPC network. To do this, use the gcloud compute firewall-rules create command to create a network egress firewall rule. This rule applies to the IP address of an endpoint. For the rule, define the source to be all VMs in the VPC network and specify a tag or service account. Limitations Troubleshoot

This section contains information about issues associated with Cloud SQL instances with Private Service Connect enabled along with steps for troubleshooting the issues.

Issue Troubleshooting The service attachment of the instance doesn't accept the Private Service Connect endpoint.
  1. Check the endpoint's status. gcloud

    To check the status, use the
    gcloud compute forwarding-rules describe command.

    gcloud compute forwarding-rules describe ENDPOINT_NAME \
    --project=PROJECT_ID \
    --region=REGION_NAME \
    | grep pscConnectionStatus

    Make the following replacements:

    REST

    Before using any of the request data, make the following replacements:

    HTTP method and URL:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules/ENDPOINT_NAME

    To send your request, expand one of these options:

    curl (Linux, macOS, or Cloud Shell) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login , or by using Cloud Shell, which automatically logs you into the gcloud CLI . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules/ENDPOINT_NAME"
    PowerShell (Windows) Note: The following command assumes that you have logged in to the gcloud CLI with your user account by running gcloud init or gcloud auth login . You can check the currently active account by running gcloud auth list.

    Execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `


    -Method GET `
    -Headers $headers `
    -Uri "https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules/ENDPOINT_NAME" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    {
      "kind": "compute#forwardingRule",
      "id": "ENDPOINT_ID",
      "creationTimestamp": "2024-05-09T12:03:21.383-07:00",
      "name": "ENDPOINT_NAME",
      "region": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME",
      "IPAddress": "IP_ADDRESS",
      "target": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/serviceAttachments/SERVICE_ATTACHMENT_NAME",
      "selfLink": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/forwardingRules/ENDPOINT_NAME",
      "network": "https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/default",
      "serviceDirectoryRegistrations": [
        {
          "namespace": "goog-psc-default"
        }
      ],
      "networkTier": "PREMIUM",
      "labelFingerprint": "LABEL_FINGERPRINT_ID",
      "fingerprint": "FINGERPRINT_ID",
      "pscConnectionId": "CONNECTION_ID",
      "pscConnectionStatus": "ACCEPTED",
      "allowPscGlobalAccess": true
    }
    
  2. Verify that the status of the endpoint is ACCEPTED. If the status is PENDING, then the instance isn't allowing the Google Cloud project that contains the endpoint. Make sure that the network project in which the endpoint is created is allowed. For more information, see Edit an instance with Private Service Connect enabled.
ERROR: (gcloud.compute.forwarding-rules.create) Could not fetch resource: The resource 'projects/PROJECT_ID/regions/REGION/subnetworks/SUBNET_NAME' was not found This error message can occur when reserving a static internal IP address for the Private Service Connect endpoint. Make sure the subnet specified exists in the project specified by the URI. If you want to create an endpoint in a service project but use a subnet from a Shared VPC network, you need to specify the subnet by its URI and use the host project's project ID in the URI. For more information, see Create the endpoint manually. ERROR: (gcloud.compute.forwarding-rules.create) Could not fetch resource: - The resource 'projects/PROJECT_ID/global/networks/NETWORK_NAME' was not found This error message can occur when you create a Private Service Connect endpoint manually. Make sure the network specified exists in the project specified by the URI. If you want to create an endpoint in a service project but use a Shared VPC network, you need to specify the network by its URI and use the host project's project ID in the URI. For more information, see Create the endpoint manually. What's next

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-07-09 UTC.

[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-07-09 UTC."],[],[]]


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4