Search connections (v2)

Search for connections in a Google Cloud project.

Code sample

Java

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.Connection;
import com.google.privacy.dlp.v2.SearchConnectionsRequest;
import java.io.IOException;

public class SearchConnections {

  public static void main(String[] args) throws Exception {
    // Provide the Google Cloud project ID to search connections in
    String projectId = "example-project-id";
    // Set locationId to "-" to search across all locations in the project
    String locationId = "-";
    searchConnections(projectId, locationId);
  }

  public static void searchConnections(String projectId, String locationId) throws Exception {
    // Initialize client that will be used to send requests
    try (DlpServiceClient client = DlpServiceClient.create()) {
      // Construct the parent resource path using project ID and wildcard location ID
      String parent = String.format("projects/%s/locations/%s", projectId, locationId);

      SearchConnectionsRequest request =
          SearchConnectionsRequest.newBuilder().setParent(parent).build();

      // Send the search connections request and iterate over results
      for (Connection connection : client.searchConnections(request).iterateAll()) {
        System.out.println("Connection name: " + connection.getName());
        System.out.println("Connection state: " + connection.getState());
      }
    }
  }
}

Node.js

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {DlpServiceClient} = require('@google-cloud/dlp');
const {status} = require('@grpc/grpc-js');

const client = new DlpServiceClient();

/**
 * Searches connections in a specified Google Cloud project and location.
 *
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Google Cloud region, or '-' for all locations.
 */
async function searchConnections(projectId, locationId) {
  try {
    // The SearchConnections RPC requires the wildcard location '-'.
    if (!locationId || locationId !== '-') {
      locationId = '-';
    }
    const parent = `projects/${projectId}/locations/${locationId}`;

    const request = {
      parent,
    };

    const [connections] = await client.searchConnections(request);

    if (!connections || connections.length === 0) {
      console.log('No connections found.');
      return;
    }

    for (const connection of connections) {
      console.log(`Connection: ${connection.name}`);
      console.log(`State: ${connection.state}`);
    }
  } catch (err) {
    if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied accessing connections: ${err.message}`);
    } else if (err.code === status.NOT_FOUND) {
      console.error(`Resource not found: ${err.message}`);
    } else {
      console.error(`API error encountered: ${err.message}`);
    }
  }
}

module.exports = { searchConnections };

Python

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import google.api_core.exceptions
from google.cloud import dlp_v2

client = dlp_v2.DlpServiceClient()


def search_connections(project_id: str, location_id: str) -> None:
    """Use the search_connections method.

    Args:
        project_id: The Google Cloud project ID to search connections in.
        location_id: The geographic location, or '-' wildcard to search
          connections across all locations.
    """
    parent = f"projects/{project_id}/locations/{location_id}"

    try:
        response = client.search_connections(request={"parent": parent})
        for connection in response:
            print(f"Connection name: {connection.name}")
            print(f"State: {connection.state.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Error searching connections: {error}")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.