列出触发器

列出当前项目的所有作业触发器。

包含此代码示例的文档页面

如需查看上下文中使用的代码示例,请参阅以下文档:

代码示例

C#

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using System;

public class TriggersList
{
    public static PagedEnumerable<ListJobTriggersResponse, JobTrigger> List(string projectId)
    {
        var dlp = DlpServiceClient.Create();

        var response = dlp.ListJobTriggers(
            new ListJobTriggersRequest
            {
                Parent = new LocationName(projectId, "global").ToString(),
            });

        foreach (var trigger in response)
        {
            Console.WriteLine($"Name: {trigger.Name}");
            Console.WriteLine($"  Created: {trigger.CreateTime}");
            Console.WriteLine($"  Updated: {trigger.UpdateTime}");
            Console.WriteLine($"  Display Name: {trigger.DisplayName}");
            Console.WriteLine($"  Description: {trigger.Description}");
            Console.WriteLine($"  Status: {trigger.Status}");
            Console.WriteLine($"  Error count: {trigger.Errors.Count}");
        }

        return response;
    }
}

Go

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库

import (
	"context"
	"fmt"
	"io"
	"time"

	dlp "cloud.google.com/go/dlp/apiv2"
	"github.com/golang/protobuf/ptypes"
	"google.golang.org/api/iterator"
	dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2"
)

// listTriggers lists the triggers for the given project.
func listTriggers(w io.Writer, projectID string) error {
	// projectID := "my-project-id"

	ctx := context.Background()

	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %v", err)
	}
	defer client.Close()

	// Create a configured request.
	req := &dlppb.ListJobTriggersRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
	}
	// Send the request and iterate over the results.
	it := client.ListJobTriggers(ctx, req)
	for {
		t, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %v", err)
		}
		fmt.Fprintf(w, "Trigger %v\n", t.GetName())
		c, err := ptypes.Timestamp(t.GetCreateTime())
		if err != nil {
			return fmt.Errorf("CreateTime Timestamp: %v", err)
		}
		fmt.Fprintf(w, "  Created: %v\n", c.Format(time.RFC1123))
		u, err := ptypes.Timestamp(t.GetUpdateTime())
		if err != nil {
			return fmt.Errorf("UpdateTime Timestamp: %v", err)
		}
		fmt.Fprintf(w, "  Updated: %v\n", u.Format(time.RFC1123))
		fmt.Fprintf(w, "  Display Name: %q\n", t.GetDisplayName())
		fmt.Fprintf(w, "  Description: %q\n", t.GetDescription())
		fmt.Fprintf(w, "  Status: %v\n", t.GetStatus())
		fmt.Fprintf(w, "  Error Count: %v\n", len(t.GetErrors()))
	}

	return nil
}

Java

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.JobTrigger;
import com.google.privacy.dlp.v2.ListJobTriggersRequest;
import com.google.privacy.dlp.v2.LocationName;
import java.io.IOException;

class TriggersList {
  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    listTriggers(projectId);
  }

  public static void listTriggers(String projectId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
      // Build the request to be sent by the client
      ListJobTriggersRequest listJobTriggersRequest =
          ListJobTriggersRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .build();

      // Use the client to send the API request.
      DlpServiceClient.ListJobTriggersPagedResponse response =
          dlpServiceClient.listJobTriggers(listJobTriggersRequest);

      // Parse the response and process the results
      System.out.println("DLP triggers found:");
      for (JobTrigger trigger : response.getPage().getValues()) {
        System.out.println("Trigger: " + trigger.getName());
        System.out.println("\tCreated: " + trigger.getCreateTime());
        System.out.println("\tUpdated: " + trigger.getUpdateTime());
        if (trigger.getDisplayName() != null) {
          System.out.println("\tDisplay name: " + trigger.getDisplayName());
        }
        if (trigger.getDescription() != null) {
          System.out.println("\tDescription: " + trigger.getDescription());
        }
        System.out.println("\tStatus: " + trigger.getStatus());
        System.out.println("\tError count: " + trigger.getErrorsCount());
      }
      ;
    }
  }
}

PHP

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库

/**
 * List Data Loss Prevention API job triggers.
 */
use Google\Cloud\Dlp\V2\DlpServiceClient;

/** Uncomment and populate these variables in your code */
// $callingProjectId = 'The project ID to run the API call under';

// Instantiate a client.
$dlp = new DlpServiceClient();

$parent = "projects/$callingProjectId/locations/global";

// Run request
$response = $dlp->listJobTriggers($parent);

// Print results
$triggers = $response->iterateAllElements();
foreach ($triggers as $trigger) {
    printf('Trigger %s' . PHP_EOL, $trigger->getName());
    printf('  Created: %s' . PHP_EOL, $trigger->getCreateTime()->getSeconds());
    printf('  Updated: %s' . PHP_EOL, $trigger->getUpdateTime()->getSeconds());
    printf('  Display Name: %s' . PHP_EOL, $trigger->getDisplayName());
    printf('  Description: %s' . PHP_EOL, $trigger->getDescription());
    printf('  Status: %s' . PHP_EOL, $trigger->getStatus());
    printf('  Error count: %s' . PHP_EOL, count($trigger->getErrors()));
    $timespanConfig = $trigger->getInspectJob()->getStorageConfig()->getTimespanConfig();
    printf('  Auto-populates timespan config: %s' . PHP_EOL,
        ($timespanConfig && $timespanConfig->getEnableAutoPopulationOfTimespanConfig() ? 'yes' : 'no'));
}

Python

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库

def list_triggers(project):
    """Lists all Data Loss Prevention API triggers.
    Args:
        project: The Google Cloud project id to use as a parent resource.
    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Import the client library
    import google.cloud.dlp

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.list_job_triggers(request={"parent": parent})

    for trigger in response:
        print("Trigger {}:".format(trigger.name))
        print("  Created: {}".format(trigger.create_time))
        print("  Updated: {}".format(trigger.update_time))
        if trigger.display_name:
            print("  Display Name: {}".format(trigger.display_name))
        if trigger.description:
            print("  Description: {}".format(trigger.discription))
        print("  Status: {}".format(trigger.status))
        print("  Error count: {}".format(len(trigger.errors)))

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器